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

查看:29
本文介绍了如何在 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.

推荐答案

Guava 提供: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天全站免登陆