如何在Java列表中获得反向列表视图? [英] How to get a reversed list view on a list in Java?

查看:135
本文介绍了如何在Java列表中获得反向列表视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在列表上有一个反向列表视图(以类似于 List#sublist 的方式在列表中提供子列表视图)。是否有一些提供此功能的功能?

I want to have a reversed list view on a list (in a similar way than List#sublist provides a sublist view on a list). Is there some function which provides this functionality?

我不想制作任何类型的列表副本,也不想修改列表。

I don't want to make any sort of copy of the list nor modify the list.

在这种情况下,如果我能在列表中获得至少一个反向迭代器就足够了。

It would be enough if I could get at least a reverse iterator on a list in this case though.

另外,我知道如何自己实现这个。我只是问Java是否已经提供了这样的东西。

Also, I know how to implement this myself. I'm just asking if Java already provides something like this.

演示实现:

static <T> Iterable<T> iterableReverseList(final List<T> l) {
    return new Iterable<T>() {
        public Iterator<T> iterator() {
            return new Iterator<T>() {
                ListIterator<T> listIter = l.listIterator(l.size());                    
                public boolean hasNext() { return listIter.hasPrevious(); }
                public T next() { return listIter.previous(); }
                public void remove() { listIter.remove(); }                 
            };
        }
    };
}






我刚刚发现一些 List 实现有 descendingIterator()这就是我需要的。虽然 List 没有一般的此类实现。这有点奇怪,因为我在 LinkedList 中看到的实现通常足以使用任何 List


I just have found out that some List implementations have descendingIterator() which is what I need. Though there is no general such implementation for List. Which is kind of strange because the implementation I have seen in LinkedList is general enough to work with any List.

推荐答案

番石榴提供: Lists.reverse(List)

List<String> letters = ImmutableList.of("a", "b", "c");
List<String> reverseView = Lists.reverse(letters); 
System.out.println(reverseView); // [c, b, a]

Collections.reverse不同,这纯粹是一个视图 ...它不会改变原始列表中元素的顺序。此外,对于可修改的原始列表,对原始列表和视图的更改将反映在另一个列表中。

Unlike Collections.reverse, this is purely a view... it doesn't alter the ordering of elements in the original list. Additionally, with an original list that is modifiable, changes to both the original list and the view are reflected in the other.

这篇关于如何在Java列表中获得反向列表视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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