Sorting and reversal of elements
- Eclipse: Oxygen
- Java: 1.8
The sorting and reversal of elements from the Collections are shown in the article by the built-in functions in the collection frameworks.
The following example demonstrates the alphabetical sorting of the List of country names. sort() method will sort the elements (country names) of the LinkedList using natural ordering (alphabetically in ascending order).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class App { public static void main(String[] args) { List<String> countries = new LinkedList<>(); countries.add("India"); countries.add("USA"); countries.add("Poland"); countries.add("Egypt"); countries.add("Thailand"); countries.add("Russia"); App app = new App(); app.printList(countries); System.out.println("*************"); countries.sort(null); app.printList(countries); } void printList(List<String> list) { ListIterator<String> iterator = list.listIterator(); while (iterator.hasNext()) { System.out.println("Element: " + iterator.next()); } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
Element: India Element: USA Element: Poland Element: Egypt Element: Thailand Element: Russia ************* Element: Egypt Element: India Element: Poland Element: Russia Element: Thailand Element: USA |
Following program is the declaration for Collections.reverse() method. It reverses the current order of the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
public class App { public static void main(String[] args) { List<String> countries = new LinkedList<>(); countries.add("India"); countries.add("USA"); countries.add("Poland"); countries.add("Egypt"); countries.add("Thailand"); countries.add("Russia"); App app = new App(); app.printList(countries); System.out.println("*************"); countries.sort(null); app.printList(countries); System.out.println("*************"); Collections.reverse(countries); app.printList(countries); } void printList(List<String> list) { ListIterator<String> iterator = list.listIterator(); while (iterator.hasNext()) { System.out.println("Element: " + iterator.next()); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
Element: India Element: USA Element: Poland Element: Egypt Element: Thailand Element: Russia ************* Element: Egypt Element: India Element: Poland Element: Russia Element: Thailand Element: USA ************* Element: USA Element: Thailand Element: Russia Element: Poland Element: India Element: Egypt |
Contributed by: Poonam Tomar