Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random element from a list with stream api?

Tags:

What is the most effective way to get a random element from a list with Java8 stream api?

Arrays.asList(new Obj1(), new Obj2(), new Obj3()); 

Thanks.

like image 744
aekber Avatar asked Aug 31 '17 12:08

aekber


2 Answers

Why with streams? You just have to get a random number from 0 to the size of the list and then call get on this index:

Random r = new Random(); ElementType e = list.get(r.nextInt(list.size())); 

Stream will give you nothing interesting here, but you can try with:

Random r = new Random(); ElementType e = list.stream().skip(r.nextInt(list.size())).findFirst().get(); 

Idea is to skip an arbitrary number of elements (but not the last one!), then get the first element if it exists. As a result you will have an Optional<ElementType> which will be non empty and then extract its value with get. You have a lot of options here after having skip.

Using streams here is highly inefficient...

Note: that none of these solutions take in account empty lists, but the problem is defined on non-empty lists.

like image 85
Jean-Baptiste Yunès Avatar answered Sep 18 '22 19:09

Jean-Baptiste Yunès


There are much more efficient ways to do it, but if this has to be Stream the easiest way is to create your own Comparator, which returns random result (-1, 0, 1) and sort your stream:

 List<String> strings = Arrays.asList("a", "b", "c", "d", "e", "f");     String randomString = strings             .stream()             .sorted((o1, o2) -> ThreadLocalRandom.current().nextInt(-1, 2))             .findAny()             .get(); 

ThreadLocalRandom has ready "out of the box" method to get random number in your required range for comparator.

like image 26
RichardK Avatar answered Sep 19 '22 19:09

RichardK