3

Below is the code snippet which, as expected, is failing at compile time.

What I really want to do is to find the min and max from all the lists using streams.

public class Delete {

   public static void main(String[] args) {

      List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 677, 0);
      List<Integer> list1 = Arrays.asList(11, 12, 23, 34, 25, 77);
      List<Integer> list2 = Arrays.asList(12, 21, 30, 14, 25, 67);
      List<Integer> list3 = Arrays.asList(41, 25, 37, 84, 95, 7);

      List<List<Integer>> largeList = Arrays.asList(list, list1, list2, list3);

      System.out.println(largeList.stream().max(Integer::compare).get());
      System.out.println(largeList.stream().min(Integer::compare).get());
   }

}
Eran
  • 374,785
  • 51
  • 663
  • 734
TheMonkWhoSoldHisCode
  • 1,924
  • 2
  • 23
  • 36
  • See also http://stackoverflow.com/questions/25988707/find-max-min-sum-and-average-of-a-list/25988761#25988761 (possible duplicate but without the `flatMap` part) – Didier L Sep 14 '16 at 11:41
  • And for the `flatMap`, see http://stackoverflow.com/questions/25147094/turn-a-list-of-lists-into-a-list-using-lambdas – Tunaki Sep 14 '16 at 13:08

2 Answers2

8

You have to flatten the elements of all the Lists into a single Stream<Integer> in order for your code to work :

System.out.println(largeList.stream().flatMap(List::stream).max(Integer::compare).get());
System.out.println(largeList.stream().flatMap(List::stream).min(Integer::compare).get());

This is not very efficient, though, since you process the Lists twice in order to find both min and max, and you can get the same data (and more) in a single processing by using IntStream::summaryStatistics() :

IntSummaryStatistics stats = largeList.stream().
                                      .flatMap(List::stream)
                                      .mapToInt(Integer::intValue)
                                      .summaryStatistics();
System.out.println(stats.getMin());
System.out.println(stats.getMax());
Eran
  • 374,785
  • 51
  • 663
  • 734
2

Try this:

largeList.stream().flatMap(List::stream).max(Integer::compare).get();
Shadov
  • 5,256
  • 2
  • 20
  • 34