Java – How to convert LinkedList to contain unique elements in Ascending-order ?

In this article, we will discuss how to sort contents of LinkedList in ascending order containing only unique elements

1. Approach :

  • Convert LinkedList into TreeSet which stores elements in default natural ordering for String objects
  • Also, TreeSet allows only unique elements and maintains ascending-order

2. To sort LinkedList contents in ascending-order :

Steps:

  1. Iterate through ArrayList to check duplicate elements
  2. Create TreeSet using inter-conversion collection constructors
  3. Add ArrayList object to TreeSet’ constructor-argument
  4. Again, iterate through TreeSet which stores only unique elements
  5. 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-loop
		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

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Conversion of HashSet to Arrays
Java - Conversion of ArrayList into HashSet to remove duplicate elements