In this article, we will discuss how to sort contents of LinkedList in ascending order containing only unique elements
Approach :
- convert to TreeSet
- which allows only unique elements and maintains ascending-order
- which uses default natural ordering for String objects
To sort LinkedList contents in ascending-order :
Steps:
- Iterate through ArrayList to check duplicate elements
- Create TreeSet using inter-conversion collection constructors
- Add ArrayList object to TreeSet’ constructor-argument
- Again, iterate through TreeSet which stores only unique elements
- Note: If NULL is present; NullPointerException will be thrown (starting Java 1.7 version)
SortingLinkedListContentsInAscendingOrder.java
package in.bench.resources.java.collections; import java.util.LinkedList; import java.util.TreeSet; public class SortingLinkedListContentsInAscendingOrder { public static void main(String[] args) { // creating LinkedList object of type String LinkedList<String> companies = new LinkedList<String>(); // adding elements to LinkedList object companies.add("Oracle"); companies.add("Google"); companies.add("LinkedIn"); companies.add("Facebook"); companies.add("Oracle"); companies.add("Amazon"); companies.add("Google"); // Iterating using enhanced for-looap System.out.println("Before Sorting : Insertion Order\n"); for(String company : companies) { System.out.println(company); } // convert to TreeSet TreeSet<String> ts = new TreeSet<String>(companies); // reverse order of LinkedList contents System.out.println("\n\n\nTreeSet : unique elements " + "and ascending order\n"); for(String company : ts) { System.out.println(company); } } }
Output:
Before Sorting : Insertion Order Oracle Google LinkedIn Facebook Oracle Amazon Google TreeSet : unique elements and ascending order Amazon Facebook Google LinkedIn Oracle
From above example, LinkedList
- allows duplicate elements
- null object is allowed
- while iterating insertion-order is maintained
From above example, TreeSet
- doesn’t allow duplicate elements
- while iterating, retrieve elements in ascending-order
References:
- https://docs.oracle.com/javase/tutorial/collections/intro/
- https://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/list.html
- https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
- https://docs.oracle.com/javase/7/docs/api/java/util/List.html
- https://docs.oracle.com/javase/8/docs/api/java/util/List.html
- https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
Happy Coding !!
Happy Learning !!