【问题标题】:java stream Collectors without mapper? [duplicate]没有映射器的java流收集器? [复制]
【发布时间】:2020-10-31 20:44:06
【问题描述】:
我想用整数调用Collectors.summarizingInt。到目前为止我看到的例子是在一个有(比如说)员工的集合上,然后被称为collect(Collecters.summorizingInt(Employee::getWage))。对于裸整数 summorizingInt 需要一个参数,所以我可以这样做 collect(Collectors.summarizingInt((i) -> i)) 但提供一个自我映射器感觉有点奇怪。
有其他选择吗?
【问题讨论】:
标签:
java
stream
summarize
【解决方案1】:
另一种选择是结合mapToInt() 将其转换为IntStream,然后在其上调用summaryStatistics():
IntSummaryStatistics summaryStatistics = Set.of(1, 3, 4)
.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
【解决方案2】:
Set<Integer> integers;
integers.stream().collect(
Collectors.summarizingInt(Integer::intValue));