list.stream方法的統計操作可以使用collect(Collectors.summarizingInt())方法來進行統計,可以統計List中元素的個數、總和、平均值、最大值和最小值等信息。示例如下:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Count: " + stats.getCount());
System.out.println("Sum: " + stats.getSum());
System.out.println("Average: " + stats.getAverage());
System.out.println("Max: " + stats.getMax());
System.out.println("Min: " + stats.getMin());
輸出結果為:
Count: 5
Sum: 15
Average: 3.0
Max: 5
Min: 1