EN
Java - get random element from list
12
points
1. Get random element from list with ThreadLocalRandom
public static Integer randomElement() {
List<Integer> list = Arrays.asList(11, 22, 33, 44, 55, 66, 77);
int size = list.size();
int randIdx = ThreadLocalRandom.current().nextInt(size);
Integer randomElem = list.get(randIdx);
return randomElem;
}
Example:
System.out.println(randomElement()); // 77
System.out.println(randomElement()); // 11
System.out.println(randomElement()); // 33