Reverse List
The Collections class provides five algorithms for doing routine data manipulation on List objects, all of which are pretty straightforward:
reverse — reverses the order of the elements in a List.
fill — overwrites every element in a List with the specified value. This operation is useful for reinitializing a List.
copy — takes two arguments, a destination List and a source List, and copies the elements of the source into the destination, overwriting its contents. The destination List must be at least as long as the source. If it is longer, the remaining elements in the destination List are unaffected.
swap — swaps the elements at the specified positions in a List.
addAll — adds all the specified elements to a Collection. The elements to be added may be specified individually or as an array.
Below two demo shows how to reverse list using java program. Example 1 using for reverse loop and second example is using Collections API reverse method to reverse list:
reverse list example:
package com.javahonk; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ReverseListExample { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("3"); list.add("5"); list.add("2"); list.add("1"); System.out.println("Example reverse logic 1\n"); System.out.println(reverseList(list)); System.out.println("Example reverse logic 2\n"); Collections.reverse(list); System.out.println(list); } static List<String> reverseList(List<String> myList) { List<String> invertedList = new ArrayList<String>(); for (int i = myList.size() - 1; i >= 0; i--) { invertedList.add(myList.get(i)); } return invertedList; } }
Output: