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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)