有没有办法“扩大”?使用流API将对象列表放入更大的列表中? [英] Is there a way to "expand" a list of objects into a bigger list with stream API?

查看:83
本文介绍了有没有办法“扩大”?使用流API将对象列表放入更大的列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个例子:我有一个RangeSet列表,其中包含例如时间戳。我想使用java8流而不是命令式方式获取范围的总持续时间:

Consider this example: I have a list of RangeSet that contains, for instance, timestamps. I want to get the total duration of ranges using java8 streams instead of the imperative way:

// "list" is List<RangeSet<Long>>

long totalTime = list.stream()
    .expand(rangeset -> rangeset.asRanges())
    .map(range -> range.upperEndpoint() - range.lowerEndpoint())
    .reduce(0, (total, time) -> total + time);

扩展当然不存在;我们的想法是将流中的每个单个对象转换为其他对象的列表,并将该列表添加到结果流中。

The "expand" of course doesn't exist ; the idea is it would convert each single object in the stream to a list of other objects, and add that list to the resulting stream.

是否有类似的或其他类似的东西如何顺利地做到这一点?

Is there something similar, or another way to do it fluently?

推荐答案

看起来你只是在寻找 Stream.flatMap ,例如

It looks like you're just looking for Stream.flatMap, e.g.

long totalTime = list.stream()
    .flatMap(rangeset -> rangeset.asRanges().stream())
    .map(range -> range.upperEndpoint() - range.lowerEndpoint())
    .reduce(0, (total, time) -> total + time);

这篇关于有没有办法“扩大”?使用流API将对象列表放入更大的列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆