Mahesha999
Mahesha999

Reputation: 24731

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?

Upvotes: 10

Views: 7443

Answers (5)

ernest_k
ernest_k

Reputation: 45319

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

Upvotes: 20

achAmh&#225;in
achAmh&#225;in

Reputation: 4266

If you ever get stuck with < Java8, a simple loop should suffice:

int max = 0;
for (List list : lists) {
    if (list.size() > max) {
        max = list.size();
    }
}

Upvotes: 3

Veselin Davidov
Veselin Davidov

Reputation: 7081

To get the longest list with reduce you can do:

    Optional<List> list=lists.stream().reduce((a, b) -> a.size()>b.size()? a:b);

This reduces your list of strings to a single list based on size (that list being Optional). To print its size you can do:

    list.ifPresent((a)-> System.out.println(a.size()));

Or a one liner would be:

    lists.stream().reduce((a, b) -> a.size()>b.size()? a:b).ifPresent((a)-> System.out.println(a.size()));

Upvotes: 2

rrobby86
rrobby86

Reputation: 1474

You can use a map operation to get the size rather than a reduce one, then you can find the maximum with the built-in method max (which returns an OptionalInt, so you use get to return an int)

lists.stream().mapToInt(x -> x.size()).max().getAsInt()

Upvotes: 1

jahra
jahra

Reputation: 1235

If you need to know only the size, but not the list itself.

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);
lists.stream().map(List::size).max(Comparator.naturalOrder()).get();

Upvotes: 6

Related Questions