4

I am working with the IntSummaryStatistics class to calculate out the statistics for my class. I searched for three particular 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 better approach? Which one we should prefer over other?

KayV
  • 12,987
  • 11
  • 98
  • 148

1 Answers1

4

I'd opt to:

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, it's exactly what IntStream.summaryStatistics does, just written explicitly. So no advantage of the first option.

I'd go with a slightly modified second option because the collector better represents the business operation "summarization of order entry amounts" from my point of view.

lexicore
  • 42,748
  • 17
  • 132
  • 221
  • 1
    There’s no fundamental difference between `.mapToInt(OrderEntry::getAmount).summaryStatistics()` and `.collect(Collectors.summarizingInt(OrderEntry::getAmount))`. That’s more a matter of taste. – Holger Dec 06 '16 at 09:03
  • @lexicore I think collect(Collectors.summarizingInt(OrderEntry::getAmount)) and collect( Collectors.summarizingInt(o -> o.getAmount())); are the same. Isn't it? – KayV Dec 06 '16 at 09:05
  • 2
    @KaranVerma Yes and no. Yes, this will give you the same result. No, in the second case you write out a lambda instead of using an existing method. I'd definitely prefer `OrderEntry::getAmount`. Why writing lambdas if the method is already there? – lexicore Dec 06 '16 at 09:12