栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用单个流操作从对象获取多个值?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用单个流操作从对象获取多个值?

与类推

IntSummaryStatistics
,创建一个
PointStatistics
收集所需信息的类。它定义了两种方法:一种用于记录a的值
Point
,一种用于组合两个的值
Statistics

class PointStatistics {    private int minX = Integer.MAX_VALUE;    private int maxX = Integer.MIN_VALUE;    private int minY = Integer.MAX_VALUE;    private int maxY = Integer.MIN_VALUE;    public void accept(Point p) {        minX = Math.min(minX, p.x);        maxX = Math.max(maxX, p.x);        minY = Math.min(minY, p.y);        maxY = Math.max(minY, p.y);    }    public void combine(PointStatistics o) {        minX = Math.min(minX, o.minX);        maxX = Math.max(maxX, o.maxX);        minY = Math.min(minY, o.minY);        maxY = Math.max(maxY, o.maxY);    }    // getters}

然后,您可以将收集

Stream<Point>
到中
PointStatistics

class Program {    public static void main(String[] args) {        List<Point> points = new ArrayList<>();        // populate 'points'        PointStatistics statistics = points         .stream()         .collect(PointStatistics::new, PointStatistics::accept, PointStatistics::combine);    }}

更新

我完全对 OP得出的结论感到困惑,所以我决定编写JMH基准测试。

基准设置:

# JMH version: 1.21# VM version: JDK 1.8.0_171, Java HotSpot(TM) 64-Bit Server VM, 25.171-b11# Warmup: 1 iterations, 10 s each# Measurement: 10 iterations, 10 s each# Timeout: 10 min per iteration# Benchmark mode: Average time, time/op

对于每次迭代,我都生成大小为100K,1M,10M 的随机

Point
s(
new Point(random.nextInt(),random.nextInt())
)共享列表。

结果是

100K

Benchmark  Mode  Cnt  Score   Error  UnitscustomCollector       avgt   10  6.760 ± 0.789  ms/opforEach    avgt   10  0.255 ± 0.033  ms/opfourStreamsavgt   10  5.115 ± 1.149  ms/opstatistics avgt   10  0.887 ± 0.114  ms/optwoStreams avgt   10  2.869 ± 0.567  ms/op

1M

Benchmark  Mode  Cnt   Score   Error  UnitscustomCollector       avgt   10  68.117 ± 4.822  ms/opforEach    avgt   10   3.939 ± 0.559  ms/opfourStreamsavgt   10  57.800 ± 4.817  ms/opstatistics avgt   10   9.904 ± 1.048  ms/optwoStreams avgt   10  32.303 ± 2.498  ms/op

10M

Benchmark  Mode  Cnt    Score     Error  UnitscustomCollector       avgt   10  714.016 ± 151.558  ms/opforEach    avgt   10   54.334 ±   9.820  ms/opfourStreamsavgt   10  699.599 ± 138.332  ms/opstatistics avgt   10  148.649 ±  26.248  ms/optwoStreams avgt   10  429.050 ±  72.879  ms/op


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/609987.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号