Collect successive pairs from a stream(从流中收集连续对)
问题描述
给定一个流,例如 { 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).
这篇关于从流中收集连续对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从流中收集连续对
基础教程推荐
- 将 Windows 证书导入 Java 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- JPA惰性列表上的流 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
