What is the Simplest Way to Reverse an ArrayList?

前端 未结 10 970
伪装坚强ぢ
伪装坚强ぢ 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: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 someDummyList = getDummyList();
            System.out.println(someDummyList);
            int size = someDummyList.size() - 1;
            ArrayList someDummyListRev = IntStream.rangeClosed(0,size).mapToObj(i->someDummyList.get(size-i)).collect(Collectors.toCollection(ArrayList::new));
            System.out.println(someDummyListRev);
        }
    
        private static ArrayList 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.

提交回复
热议问题