How to Reverse an Object Collection in Java
This example shows how reverse the contents of a LinkedList by calling the method of the Collections: class: Collections.reverse() . We chose LinkedList as our collection of objects. The same method also applies to other collections that inherit from the java.util.Collection. You have to pass the LinkedList instance as a parameter. This method is used to reverse the order of the items in the list.
Example:
This code handles the following three collections of java objects: ArrayList, LinkedList, and Vector.
Example:
This code handles the following three collections of java objects: ArrayList, LinkedList, and Vector.
import java.util.Collections;Result:
import java.util.LinkedList;
public class inverse_collection {
public static void main(String[] args) {
LinkedListllist = new LinkedList ();
llist.add("1");
llist.add("2");
llist.add("3");
llist.add("4");
System.out.println("Before inversion: "+llist);
Collections.reverse(llist);
System.out.println("After inversion: "+llist);
}
}
Before inversion: [1, 2, 3, 4]Collections that inherit from java.util.Set and java.util.Map are not supported by the Collections.reverse() method. However, a partial solution is possible:
After inversion: [4, 3, 2, 1]
- Create an instance of ArrayList with a collection from the Set interface or Map
- Apply the Collections.reverse() method on the ArrayList
- Items cannot be copied back to the original collection. What for? Because the Set interface does not guarantee the insertion order.
Note: The Map interface is a key/value hash table. This means that we only have the choice to invert either the keys or the values without copying the results back into the collection that implements Map, because it doesn't keep the order of the elements. |
Example of TreeSet:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
public class Intervert {
public static void main(String[] args) {
// creating TreeSet
TreeSettset = new TreeSet ();
// add elements to treeset
tset.add("a");
tset.add("b");
tset.add("c");
Iterator iterator = tset.iterator();
// display of TreeSet
System.out.println("Treeset elements in ascending order: ");
while (iterator.hasNext()){
System.out.println(iterator.next());
}
Listlist = new ArrayList (tset);
Collections.reverse(list);
// display values inversely
System.out.println("The elements of treeset in reverse order: ");
for(String s:list)
System.out.println(s);
}
}
Output:
Treeset elements in ascending order:
a
b
c
treeset elements in reverse order:
c
b
a