如何在 Java 中的列表上获得反向列表视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3962766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:39:40  来源:igfitidea点击:

How to get a reversed list view on a list in Java?

javalistcollectionsiteratorreverse

提问by Albert

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

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

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.

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

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 Listimplementations 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 LinkedListis general enough to work with any List.

我刚刚发现有些List实现descendingIterator()是我需要的。尽管List. 这有点奇怪,因为我看到的实现LinkedList足够通用,可以与任何List.

采纳答案by ColinD

Guavaprovides this: Lists.reverse(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]

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.

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

回答by kkress

Its not exactly elegant, but if you use List.listIterator(int index) you can get a bi-directional ListIterator to the end of the list:

它不是很优雅,但如果你使用 List.listIterator(int index) 你可以得到一个双向 ListIterator 到列表的末尾:

//Assume List<String> foo;
ListIterator li = foo.listIterator(foo.size());

while (li.hasPrevious()) {
   String curr = li.previous()
}

回答by Bozho

java.util.Dequehas descendingIterator()- if your Listis a Deque, you can use that.

java.util.Dequehas descendingIterator()- 如果您List是 a Deque,则可以使用它。

回答by jcalvert

Use the .clone() method on your List. It will return a shallow copy, meaning that it will contain pointers to the same objects, so you won't have to copy the list. Then just use Collections.

在您的列表中使用 .clone() 方法。它将返回一个浅拷贝,这意味着它将包含指向相同对象的指针,因此您不必复制列表。然后只需使用集合。

Ergo,

因此,

Collections.reverse(list.clone());

If you are using a Listand don't have access to clone()you can use subList():

如果您使用的是 aList并且无权访问,则clone()可以使用subList()

List<?> shallowCopy = list.subList(0, list.size());
Collections.reverse(shallowCopy);

回答by CocheLee

I know this is an old post but today I was looking for something like this. In the end I wrote the code myself:

我知道这是一个旧帖子,但今天我正在寻找这样的东西。最后我自己写了代码:

private List reverseList(List myList) {
    List invertedList = new ArrayList();
    for (int i = myList.size() - 1; i >= 0; i--) {
        invertedList.add(myList.get(i));
    }
    return invertedList;
}

Not recommended for long Lists, this is not optimized at all. It's kind of an easy solution for controlled scenarios (the Lists I handle have no more than 100 elements).

不推荐用于长列表,这根本没有优化。对于受控场景,这是一种简单的解决方案(我处理的列表不超过 100 个元素)。

Hope it helps somebody.

希望它可以帮助某人。

回答by jhdrosos

You can also do this:

你也可以这样做:

static ArrayList<String> reverseReturn(ArrayList<String> alist)
{
   if(alist==null || alist.isEmpty())
   { 
       return null;
   }

   ArrayList<String> rlist = new ArrayList<>(alist);

   Collections.reverse(rlist);
   return rlist;
}

回答by Shakeeb Ayaz

If i have understood correct then it is one line of code .It worked for me .

如果我理解正确,那么它就是一行代码。它对我有用。

 Collections.reverse(yourList);

回答by Museful

I use this:

我用这个:

public class ReversedView<E> extends AbstractList<E>{

    public static <E> List<E> of(List<E> list) {
        return new ReversedView<>(list);
    }

    private final List<E> backingList;

    private ReversedView(List<E> backingList){
        this.backingList = backingList;
    }

    @Override
    public E get(int i) {
        return backingList.get(backingList.size()-i-1);
    }

    @Override
    public int size() {
        return backingList.size();
    }

}

like this:

像这样:

ReversedView.of(backingList) // is a fully-fledged generic (but read-only) list

回答by Krishna Kumar Chourasiya

Collections.reverse(nums) ... It actually reverse the order of the elements. Below code should be much appreciated -

Collections.reverse(nums) ... 它实际上颠倒了元素的顺序。下面的代码应该非常感谢 -

List<Integer> nums = new ArrayList<Integer>();
nums.add(61);
nums.add(42);
nums.add(83);
nums.add(94);
nums.add(15);
//Tosort the collections uncomment the below line
//Collections.sort(nums); 

Collections.reverse(nums);

System.out.println(nums);

Output: 15,94,83,42,61

输出:15,94,83,42,61

回答by fede1608

You can also invert the position when you request an object:

您还可以在请求对象时反转位置:

Object obj = list.get(list.size() - 1 - position);