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

前端 未结 12 757
自闭症患者
自闭症患者 2020-11-28 21:05

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

相关标签:
12条回答
  • 2020-11-28 21:31

    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).

    Hope it helps somebody.

    0 讨论(0)
  • 2020-11-28 21:33

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

     Collections.reverse(yourList);
    
    0 讨论(0)
  • 2020-11-28 21:34

    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
    
    0 讨论(0)
  • 2020-11-28 21:36

    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:

    //Assume List<String> foo;
    ListIterator li = foo.listIterator(foo.size());
    
    while (li.hasPrevious()) {
       String curr = li.previous()
    }
    
    0 讨论(0)
  • 2020-11-28 21:36

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

    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

    0 讨论(0)
  • 2020-11-28 21:37

    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;
    }
    
    0 讨论(0)
提交回复
热议问题