Shervin Asgari
Shervin Asgari

Reputation: 24499

Java 8 Stream - Find largest nested list

I have a Collection<List<SomeObject>> values

How can I find the collection with the largest list using Streams?

I have tried something like this, but it doesn't quite work

values.stream().max(e -> e.stream().max(List::size).get()).get()

But I get compilation error. Any ideas?

Upvotes: 5

Views: 4170

Answers (2)

Tagir Valeev
Tagir Valeev

Reputation: 100169

My StreamEx library provides a ready collector to find all the maximal elements:

List<List<SomeObject>> result = values.stream()
                .collect(MoreCollectors.maxAll(Comparator.comparingInt(List::size)));

Upvotes: 3

Louis Wasserman
Louis Wasserman

Reputation: 198023

I think you want

 values.stream().max(Comparator.comparingInt(List::size)).get()

If you need duplicates, the best solution I can think of would be something like

values.stream()
   .collect(Collector.of(
      ArrayList::new,
      (List<List<SomeObject>> best, List<SomeObject> elem) -> {
        if (best.isEmpty()) {
          best.add(elem);
        } else if (best.get(0).size() < elem.size()) {
          best.clear();
          best.add(elem);
        }
      },
      (best1, best2) -> {
        if (best1.isEmpty() || best2.isEmpty()
              || best1.get(0).size() == best2.get(0).size()) {
          best1.addAll(best2);
          return best1;
        } else if (best1.get(0).size() > best2.get(0).size()) {
          return best1;
        } else {
          return base2;
        }
      }));

Upvotes: 15

Related Questions