Search code examples
javastreamsummarize

java stream Collectors without mapper?


I want to call Collectors.summarizingInt on a set with Integers. Examples I have seen so far are on a Set with (say) Employees and are then called as collect(Collecters.summorizingInt(Employee::getWage)). For the bare Integers summorizingInt needs an argument so I can do collect(Collectors.summarizingInt((i) -> i)) but it feels a bit strange to provide a self mapper.

Are there alternatives?


Solution

  • Another option could be combining mapToInt() to convert it to the IntStream and then call summaryStatistics() on it:

     IntSummaryStatistics summaryStatistics = Set.of(1, 3, 4)
                    .stream()
                    .mapToInt(Integer::intValue)
                    .summaryStatistics();