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

  • A+
Category:Languages

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?


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() 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: