[英]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.shuffle
和Collections.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並在循環中生成一個索引,以從列表中選擇和檢索。
如果此處考慮安全性,請嘗試以下方法之一:
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));
}
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.