如何在Java中颠倒列表? [英] How to reverse a list in Java?

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

问题描述

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



我不想做任何类型的列表副本或修改列表。



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






此外,我知道如何自己实现。



演示实现:

 

code> static< T>可迭代的< 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 。 p>

解决方案

Guava 提供此功能: a href =http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Lists.html#reverse%28java.util.List%29> Lists.reverse (List)

 列表< String> letters = ImmutableList.of(a,b,c); 
List< String> reverseView = Lists.reverse(letters);
System.out.println(reverseView); // code>,这只是一个视图 ...它不会改变原始列表中的元素的排序。此外,使用可修改的原始列表,对原始列表和视图的更改都反映在另一个列表中。


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.


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

Demo implementation:

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(); }                 
            };
        }
    };
}


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 provides this: Lists.reverse(List)

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

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天全站免登陆