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]
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. |
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);
}
}
Treeset elements in ascending order:
a
b
c
treeset elements in reverse order:
c
b
a
Please disable your ad blocker and refresh the window to use this website.