簡體   English   中英

從arraylist隨機獲取對象

[英]Getting objects randomly from arraylist

我有一個數組,其中包含50個Object

我想每次啟動應用程序時從該List隨機獲取4個對象。

然后把它們放在Map

如何從數組中隨機抽取4個對象?

這是我的代碼示例:

ArrayList<Deal> dealsTodayArray = dealsToday.getDeals(); 
Map<String, Object> map = new HashMap<String, Object>();
map.put("dealsTodayFirst", dealsTodayFirst);
map.put("dealsTodaySecond", dealsTodaySecond);
map.put("dealsTodayThird", dealsTodayThird);
map.put("dealsTodayForth", dealsTodayForth);

嘗試將Collections.shuffleCollections.subList結合使用:

List<String> myStrings = new ArrayList<String>();
myStrings.add("a");
myStrings.add("b");
myStrings.add("c");
myStrings.add("d");
myStrings.add("e");
myStrings.add("f");
Collections.shuffle(myStrings);
System.out.println(myStrings.subList(0, 4));

輸出 (可能但不保證每次執行都會改變):

[c, b, f, d]

您可以使用Random類在ArrayList的范圍內生成隨機索引。

Random rand = new Random();
int size = dealsTodayArray.size();
map.put("dealsTodayFirst", dealsTodayArray.get(rand.nextInt(size)));
// repeat with the 3 others...

您需要對Random類使用get方法。 使用Random類生成元素的索引,並使用get方法檢索它。

Random random = new Random();

Deal deal = dealsTodayArray.get(random.nextInt(50));
// And repeat a few more times.

創建一個Random並在循環中生成一個索引,以從列表中選擇和檢索。

如果此處考慮安全性,請嘗試以下方法之一:

方法1

Random sr = new SecureRandom();
Collections.shuffle(dealsTodayArray, sr);

final int N = 4;
for( int i=0; i<N; i++ ) {
    map.put("dealsTodayFirst", dealsTodayArray.get(i));
}

方法2

Random sr = new SecureRandom();
final int N = 4;
final int len = dealsTodayArray.size();
for( int i=0; i<N; i++ ) {
    map.put("dealsTodayFirst", dealsTodayArray.get(sr.nextInt(len)));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM