Java – How to reverse LinkedHashSet contents ?

In this article, we will discuss how to reverse the contents of LinkedHashSet

Key points about LinkedList:

  • LinkedHashSet maintains insertion-order
  • It uses doubly-linked list and hashtable to store element/objects

To reverse LinkedHashSet contents:

  • We can iterate through LinkedHashSet in reverse order
  • By converting LinkedHashSet into ArrayList and using Collections class’ reverse() method
  • Method signature: public static void reverse(List list);
  • This method is used to reverse the order of ArrayList contents i.e.; reverse-order of insertion-order

ReverseLinkedHashSetContents.java

package in.bench.resources.java.collections;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Collections;

public class ReverseLinkedHashSetContents {

	public static void main(String[] args) {

		// creating LinkedHashSet object of type String
		LinkedHashSet<String> lhsCompanies =
				new LinkedHashSet<String>();


		// adding elements to LinkedHashSet object
		lhsCompanies.add("LinkedIn");
		lhsCompanies.add("Amazon");
		lhsCompanies.add("Google");
		lhsCompanies.add("Apple");
		lhsCompanies.add("Facebook");
		lhsCompanies.add("Oracle");
		lhsCompanies.add("Microsoft");


		// Iterating using enhanced for-loop
		System.out.println("Insertion Order: Iterating LinkedHashSet\n");
		for(String company : lhsCompanies) {
			System.out.println(company);

		}

		// convert to ArrayList
		ArrayList<String> alCompanies =
				new ArrayList<String>(lhsCompanies);


		// to reverse LinkedHashSet contents
		Collections.reverse(alCompanies);


		// reverse order of LinkedHashSet contents
		System.out.println("\n\n\nReverse Order of LinkedHashSet\n");
		for(String company : alCompanies) {
			System.out.println(company);
		}
	}
}

Output:

Insertion Order: Iterating LinkedHashSet

LinkedIn
Amazon
Google
Apple
Facebook
Oracle
Microsoft



Reverse Order of LinkedHashSet

Microsoft
Oracle
Facebook
Apple
Google
Amazon
LinkedIn

From above example, LinkedHashSet

  • doesn’t allow duplicate elements
  • maximum of one null object is allowed
  • while iterating, maintains insertion-order

References:

Happy Coding !!
Happy Learning !!

Java - Iterate through Vector in 5 ways
Java 8 - Iterating Set using forEach() method