如何在Java 8中以相反的顺序从列表中获取有序流 [英] How to get ordered stream from a list in reverse order in Java 8

查看:105
本文介绍了如何在Java 8中以相反的顺序从列表中获取有序流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种理智的方法来从列表中获取有序流(具体来说,数组列表,但它无关紧要),它将元素与它们在原始列表中的方式相反?

Is there a sane way to get an ordered stream from a list (array list specifically, but it shouldn't matter) that streams elements in reverse of how they are in the original list?

我正在寻找一种不涉及缓冲数据的解决方案(收集器,另一个列表,数组等,因为它们复制了浪费的容器),或者使用 Collections.reverse (因为它修改了列表)。

I'm looking for a solution that doesn't involve buffering data in anything (collector, another list, array, etc, because they copy the container which is wasteful), or uses Collections.reverse (because it modifies the list).

到目前为止,我在这里看到的最简洁的方法是实现我自己的版本 Spliterator 那是 ORDERED 并反向推进列表,或实现 Iterator 反向迭代,并在其上使用 Spliterators.spliteratorUnknownSize(iterator,ORDERED)

So far, the cleanest ways that I see here is to implement my own version of Spliterator that's ORDERED and advances through the list in reverse, or implement an Iterator that iterates in reverse, and use Spliterators.spliteratorUnknownSize(iterator,ORDERED) on it.

请注意,此问题与 Java 8流逆向订单不同:其他问题请求如何扭转圣令人满意(这在一般情况下是不可能的),并且答案提供了以某种方式反转源(我不想做),然后传输反向源。逆转源的成本是O(N),如果可能的话我想完全避免它。

Note this question is different from Java 8 stream reverse order : that other question asks on how to reverse a stream (which is impossible in general case), and answers offer to reverse the source somehow (which I don't want to do), and then stream that reversed source. The cost of reversing the source is O(N), and I want to avoid it at all if possible.

推荐答案

如果你的话列表是随机访问列表,您可以简单地使用

If your List is a random access list, you may simply use

int num=list.size()-1;
IntStream.rangeClosed(0, num).mapToObj(i->list.get(num-i))

创建一个 Stream ,其特征是 ORDERED | SIZED | SUBSIZED 并提供完全拆分支持。

to create a Stream which has the characteristics ORDERED | SIZED | SUBSIZED and offers full splitting support.

对于非随机访问列表,如 LinkedList 然而,这将是一场性能灾难,无论如何使用 LinkedList

For a non-random access list like LinkedList it would be a performance disaster, however, who uses LinkedList anyway?

您也可以通过<$进行检查c $ c> list instanceof RandomAccess 首先......

You may also check via list instanceofRandomAccess first…

这篇关于如何在Java 8中以相反的顺序从列表中获取有序流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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