简体   繁体   English

使用Java流从集合中查找最小和最大数量

[英]Find the min and max number from a Collection using Java streams

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

}

You have to flatten the elements of all the List s into a single Stream<Integer> in order for your code to work : 您必须将所有List的元素展平为单个Stream<Integer> ,以便您的代码可以工作:

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 List s 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() : 但是,这不是很有效,因为您处理List两次以便同时找到minmax ,并且您可以通过使用IntStream::summaryStatistics()在单个处理中获得相同的数据(和更多IntStream::summaryStatistics()

IntSummaryStatistics stats = largeList.stream().
                                      .flatMap(List::stream)
                                      .mapToInt(Integer::intValue)
                                      .summaryStatistics();
System.out.println(stats.getMin());
System.out.println(stats.getMax());

尝试这个:

largeList.stream().flatMap(List::stream).max(Integer::compare).get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM