Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain size of largest list out of list of lists using Java 8 streams?

Say I am having following list of lists"

List l1 = Arrays.asList(1,2,3,4);
List l2 = Arrays.asList(1,2,3,4,5);
List l3 = Arrays.asList(1,2,3,4,5,6);
List<List> lists = Arrays.asList(l1,l2,l3);

How can I know size of largest list using Java 8 streams API? I thought, something like this will work:

lists.stream().reduce(Integer.MIN_VALUE, (a,b) -> Integer.max(a.size(), b.size()));

But for obvious reasons, it is giving me:

Type mismatch: cannot convert from int to List

How can I do above using Java 8 streams? (And also if there is any other better approach possible)

Also can I get reference to list with max size?

like image 250
Mahesha999 Avatar asked May 25 '18 13:05

Mahesha999


1 Answers

You can just call max:

lists.stream().mapToInt(List::size).max().getAsInt()

And to take the list with the highest size:

lists.stream().max(Comparator.comparing(List::size)).get()
like image 151
ernest_k Avatar answered Sep 22 '22 09:09

ernest_k