fbpx

Reverse a Java List, Array

Since Java 8, the order of elements in a List or its subclasses such as ArrayList can be reversed using a utility function provided as part of the Collections class.

Collections.reverse(list);

The list is reversed in place, which means the elements in the list are reversed inside the same object.

Collections.reverse(array); //DOES NOT WORK!

The implementation works only on an implementation of List. However if you would like to reverse the order of elements in an Array, and would like to do so with brevity of code without being concerned about expense of the operation, then a possible solution is as follows

List<Integer> list = Arrays.asList(array);
Collections.reverse(list);
array = list.toArray(new Integer[list.size()]);

The above code converts the array to list, reverses the list and then converts the list back to array. Please avoid this if possible, and use a List throughout your program instead of using Arrays.

%d bloggers like this: