Difference between summing Int and Collectors.summarizingInt?

I am working with the IntSummaryStatistics class to calculate statistics for my class. I was looking for three ways to calculate statistics. Here is my code:

IntSummaryStatistics stats1 = orderEntries.stream()
            .mapToInt((x) -> x.getAmount()).summaryStatistics();

IntSummaryStatistics stats2 = orderEntries.stream().collect(
            Collectors.summarizingInt(o -> o.getAmount()));

IntSummaryStatistics istats2 = orderEntries.stream().
                            collect( 
                                    () -> new IntSummaryStatistics(),
                                    (i,o) -> i.accept(o.getAmount()),
                                    (i1, i2) -> i1.combine(i2));
IntSummaryStatistics istats = IntStream.of(51,22,50,27,35).
        collect(IntSummaryStatistics::new, IntSummaryStatistics::accept, 
                IntSummaryStatistics::combine);

Which one is the best approach? Which one should we prefer over others?

+4
source share
1 answer

I would choose:

IntSummaryStatistics stats = orderEntries
    .stream()
    .collect(Collectors.summarizingInt(OrderEntry::getAmount));

This option:

IntSummaryStatistics istats = IntStream.of(51,22,50,27,35).
            collect(IntSummaryStatistics::new, IntSummaryStatistics::accept, 
                    IntSummaryStatistics::combine);

is the worst, this is exactly what it does IntStream.summaryStatistics, just written explicitly. Thus, there is no advantage to the first option.

I would go with a slightly modified second option, because the collector better reflects the business operation “summing order entry amounts” from my point of view.

+4
source

Source: https://habr.com/ru/post/1662923/


All Articles