How to reverse LinkedHashSet contents

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

LinkedHashSet maintains insertion order, as 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 into ArrayList and use 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:

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/7/docs/api/java/util/Iterator.html
https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
https://docs.oracle.com/javase/7/docs/api/java/util/class-use/HashSet.html
https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html
http://docs.oracle.com/javase/7/docs/api/index.html?java/util/class-use/LinkedHashSet.html

 

Happy Coding !!
Happy Learning !!