首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >summarizingInt与Collectors.summarizingInt的差异?

summarizingInt与Collectors.summarizingInt的差异?
EN

Stack Overflow用户
提问于 2016-12-06 07:25:58
回答 1查看 2.1K关注 0票数 4

我正在使用IntSummaryStatistics类来计算出我的类的统计数据。我寻找了三种计算统计的特殊方法。这是我的代码:

代码语言:javascript
复制
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);

哪一种方法更好?我们更喜欢哪一种?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-06 08:10:32

我会选择:

代码语言:javascript
复制
IntSummaryStatistics stats = orderEntries
    .stream()
    .collect(Collectors.summarizingInt(OrderEntry::getAmount));

这一备选方案:

代码语言:javascript
复制
IntSummaryStatistics istats = IntStream.of(51,22,50,27,35).
            collect(IntSummaryStatistics::new, IntSummaryStatistics::accept, 
                    IntSummaryStatistics::combine);

最糟糕的是,这正是IntStream.summaryStatistics所做的,只是显式地编写。所以第一种选择没有优势。

我将使用稍微修改的第二个选项,因为从我的角度来看,收集器更好地表示业务操作“订单输入金额摘要”。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40989955

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档