Languages
[Edit]
EN

Java - get random element from list

12 points
Created by:
Payne
654

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - collections

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join