What is the Simplest Way to Reverse an ArrayList?

前端 未结 10 882
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 18:10

What is the simplest way to reverse this ArrayList?

ArrayList aList = new ArrayList<>();

//Add elements to ArrayList object
aList.add(\         


        
相关标签:
10条回答
  • 2020-11-28 18:34

    Not the simplest way but if you're a fan of recursion you might be interested in the following method to reverse an ArrayList:

    public ArrayList<Object> reverse(ArrayList<Object> list) {
        if(list.size() > 1) {                   
            Object value = list.remove(0);
            reverse(list);
            list.add(value);
        }
        return list;
    }
    

    Or non-recursively:

    public ArrayList<Object> reverse(ArrayList<Object> list) {
        for(int i = 0, j = list.size() - 1; i < j; i++) {
            list.add(i, list.remove(j));
        }
        return list;
    }
    
    0 讨论(0)
  • 2020-11-28 18:35

    A little more readable :)

    public static <T> ArrayList<T> reverse(ArrayList<T> list) {
        int length = list.size();
        ArrayList<T> result = new ArrayList<T>(length);
    
        for (int i = length - 1; i >= 0; i--) {
            result.add(list.get(i));
        }
    
        return result;
    }
    
    0 讨论(0)
  • 2020-11-28 18:38

    We can also do the same using java 8.

    public static<T> List<T> reverseList(List<T> list) {
            List<T> reverse = new ArrayList<>(list.size());
    
            list.stream()
                    .collect(Collectors.toCollection(LinkedList::new))
                    .descendingIterator()
                    .forEachRemaining(reverse::add);
    
            return reverse;
        }
    
    0 讨论(0)
  • 2020-11-28 18:41

    Just in case we are using Java 8, then we can make use of Stream. The ArrayList is random access list and we can get a stream of elements in reverse order and then collect it into a new ArrayList.

    public static void main(String[] args) {
            ArrayList<String> someDummyList = getDummyList();
            System.out.println(someDummyList);
            int size = someDummyList.size() - 1;
            ArrayList<String> someDummyListRev = IntStream.rangeClosed(0,size).mapToObj(i->someDummyList.get(size-i)).collect(Collectors.toCollection(ArrayList::new));
            System.out.println(someDummyListRev);
        }
    
        private static ArrayList<String> getDummyList() {
            ArrayList dummyList = new ArrayList();
            //Add elements to ArrayList object
            dummyList.add("A");
            dummyList.add("B");
            dummyList.add("C");
            dummyList.add("D");
            return dummyList;
        }
    

    The above approach is not suitable for LinkedList as that is not random-access. We can also make use of instanceof to check as well.

    0 讨论(0)
提交回复
热议问题