簡體   English   中英

使用Java流從集合中查找最小和最大數量

[英]Find the min and max number from a Collection using Java 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());
   }

}

您必須將所有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());

但是,這不是很有效,因為您處理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