Languages
[Edit]
EN

Java - get random element from list

12 points
Created by:
AnnLen
1771

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.