Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 335
Shervin Asgari Avatar asked Jan 13 '16 20:01

Shervin Asgari


People also ask

How do you find the maximum number of lists in a stream?

Calling stream() method on the list to get a stream of values from the list. Calling mapToInt(value -> value) on the stream to get an Integer Stream. Calling max() method on the stream to get the max value.

How do you get the highest number that exists on a list in Java 8?

max() method. The idea is to convert the list into a Stream and call Stream#max() that accepts a Comparator to compare items in the stream against each other to find the maximum element, and returns an Optional containing the maximum element in the stream according to the provided Comparator .

Does streams in Java 8 have limited storage?

No storage. Streams don't have storage for values; they carry values from a source (which could be a data structure, a generating function, an I/O channel, etc) through a pipeline of computational steps.


1 Answers

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;
        }
      }));
like image 99
Louis Wasserman Avatar answered Oct 02 '22 18:10

Louis Wasserman