使用流合并两个排序的阵列在Java中
我有两个排序的整数阵列。我希望将它们合并为一个排序的阵列。我想使用Java流来实现这一目标。
我可以做一个嵌套的流吗?
Arrays.asList(nums1).stream()
.forEach(i -> Arrays.asList(nums2).stream()
.forEach(j -> //compare i,j)
.collect as list// ;
例如,[1,3,4]
和[2,5]
应返回[1,2,3,4,5]
I have two sorted integer arrays. I am looking to merge them into one sorted array. I would like to use Java Stream to achieve this.
Can I do a nested stream?
Arrays.asList(nums1).stream()
.forEach(i -> Arrays.asList(nums2).stream()
.forEach(j -> //compare i,j)
.collect as list// ;
For example, [1,3,4]
and [2,5]
should return [1,2,3,4,5]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在我的解决方案下方,o(n)的复杂时间
Below my solution with complexity time of O(n)
当我们在流管线上应用
sorted()
操作时,在引擎盖下,它将分配内存中的数组,该数组将填充流中的元素并排序。分类参考类型的数组Java使用,擅长在输入中发现排序的数据(
arrays.aslist()因此,我认为我们正在谈论对象
)。
因此,如果我们简单地将两个数据集串联起来,它仍然可以很好地表现。
output:
如果要使用有条件的逻辑获取结果排序的数组,则必须使用循环的普通
。这不是流的工作。
使用命令编程,可以像这样实现:
输出:
When we apply
sorted()
operation on a stream pipeline, under the hood it'll allocate an array in memory that will be filled with elements of the stream and sorted.To sort an array of reference type Java uses an implementation of the Timsort algorithm, which is good at spotting sorted chunks of data in the input (
Arrays.asList()
that you've used in your example expects varargsT
, so I assume we are talking about objects).Therefore, if we simply concatenate the two data sets it will still perform reasonably well.
Output:
In case if you want to use conditional logic to obtain a sorted resulting array, then you must go with a plain
for
loop. It's not a job for a stream.Using imperative programming, it can be implemented like that:
Output:
流很好,但我建议您这样的方式,因为使用溪流,您首先必须将阵列更改为流式的阵列,以便在它们上工作,这可能会变得昂贵
Streams are nice but i recommend you this way because with streams you first have to change the arrays to streams only to work on them which could get expensive