What is the simplest way to reverse this ArrayList?
ArrayList aList = new ArrayList<>();
//Add elements to ArrayList object
aList.add(\
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.