从流中收集连续对
给定一个流,例如 { 0, 1, 2, 3, 4 }
,
Given a stream such as { 0, 1, 2, 3, 4 }
,
我怎样才能最优雅地将它转换成给定的形式:
how can I most elegantly transform it into given form:
{ new Pair(0, 1), new Pair(1, 2), new Pair(2, 3), new Pair(3, 4) }
(当然,假设我已经定义了类 Pair)?
(assuming, of course, I've defined class Pair)?
这并不是严格意义上的整数或原始流.对于任何类型的流,答案都应该是通用的.
This isn't strictly about ints or primitive streams. The answer should be general for a stream of any type.
推荐答案
我的 StreamEx 库扩展了标准流提供了一个 pairMap
方法适用于所有流类型.对于原始流,它不会更改流类型,但可用于进行一些计算.最常见的用法是计算差异:
My StreamEx library which extends standard streams provides a pairMap
method for all stream types. For primitive streams it does not change the stream type, but can be used to make some calculations. Most common usage is to calculate differences:
int[] pairwiseDiffs = IntStreamEx.of(input).pairMap((a, b) -> (b-a)).toArray();
对于对象流,您可以创建任何其他对象类型.我的库不提供任何新的用户可见数据结构,例如 Pair
(这是库概念的一部分).但是,如果您有自己的 Pair
类并想使用它,则可以执行以下操作:
For object stream you can create any other object type. My library does not provide any new user-visible data structures like Pair
(that's the part of library concept). However if you have your own Pair
class and want to use it, you can do the following:
Stream<Pair> pairs = IntStreamEx.of(input).boxed().pairMap(Pair::new);
或者如果你已经有一些Stream
:
Or if you already have some Stream
:
Stream<Pair> pairs = StreamEx.of(stream).pairMap(Pair::new);
此功能是使用 自定义拆分器.它的开销非常低,并且可以很好地并行化.当然,它适用于任何流源,而不仅仅是像许多其他解决方案那样的随机访问列表/数组.在许多测试中,它表现得非常好.这里是一个 JMH 基准测试,我们使用不同的方法找到一个较大值之前的所有输入值(参见 这个问题).
This functionality is implemented using custom spliterator. It has quite low overhead and can parallelize nicely. Of course it works with any stream source, not just random access list/array like many other solutions. In many tests it performs really well. Here's a JMH benchmark where we find all input values preceding a larger value using different approaches (see this question).
相关文章