Вопрос

I have an array which has 50 Objects in it.

I want to randomly get 4 objects from that List every time app launches.

And than put them in a Map.

How can i take randomly 4 objects from array?

Here is my code sample:

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);
Это было полезно?

Решение

Try a combination of Collections.shuffle and 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));

Output (likely but not guaranteed to change at every execution):

[c, b, f, d]

Другие советы

You could use the Random class to generate random indices within the bounds of your ArrayList.

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

You need to use the get method, with the Random class. Use the Random class to generate the index of the element, and use the get method to retrieve it.

Example

Random random = new Random();

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

Create a Random and in a loop generate an index to select and retrieve from list.

If security is a concern here, try one of these approaches:

Approach 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));
}

Approach 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 с атрибуция
Не связан с StackOverflow
scroll top