List Reverse Sort Java

List Reverse Sort Java

Note: It is advised to read List Fundamentals before proceeding the following programs.

Four programs are given on List with different functionalities.

  1. List Methods: Uses frequently used methods like size(), add(), get(), contains(), indexOf(), lastIndexOf(), subList(), remove(), clear() and isEmpty().
  2. List Iteration: Comparing two lists with equals(), converting list elements to array with toArray(), printing array elements with foreach loop, printing list elements with Iterator (forward) and ListIterator (forward and backward).
  3. List Reversing Sorting: Reversing and sorting the list elements with methods asList(), sort(), reverseorder.
  4. List Unique Elements: Removing duplicate elements from list, sorting list elements, converting list to Set and again set to list.

In this third program, reversing and sorting of list elements is done with methods sort() and reverseOrder().

Example on List Reverse Sort Java


List Reverse Sort Java
Output Screen on List Reverse Sort Java

String countries[] = { “india”, “Bangladesh”, “nepal”, “Srilanka” };
List countryList =Arrays.asList(countries);

Java collections framework includes two classes Collections and Arrays. Collections is used to manipulate data structure elements and Arrays is used to manipulate array elements. asList(countries) method returns a list object countryList that contains the elements of the array countries.

Collections.sort(countryList);
System.out.println(“Case sensitive sorting: ” + countryList);
Collections.sort(countryList, String.CASE_INSENSITIVE_ORDER);

The sort() method of Collections sorts the elements in ascending order implicitly. But it makes case-sensitive order. To ignore the sensitivity, use a variable String.CASE_INSENSITIVE_ORDER.

Collections.sort(countryList, Collections.reverseOrder());

The sort() method with parameter reverseOrder() reverses the elements and sorts. The sorting affects the original elements itself.

General Exceptions raised by collections classes

IllegalStateException ConcurrentModificationException
UnsupportedOperationException NullPointerException
NoSuchElementException

Leave a Reply

Your email address will not be published. Required fields are marked *