Java 8 – How to sort HashSet ?

In this article, we will discuss how to sort HashSet in Java 8. Already, in one of the earlier article we discussed about HashSet Sorting in Ascending & Descending order

Key points about HashSet:

  • HashSet stores elements in random-order
  • Allows only unique element/objects with maximum limit of 1 null object

1. Sorting HashSet in Java 8:

  1. With simple type like String
  2. With Object

1.1 Sorting HashSet with String type

Steps:

  1. Create new HashSet object
  2. Add String element/objects to newly created HashSet
  3. Print original HashSet by iterating using enhanced forEach loop introduced in Java 1.5
  4. Sort using Java 1.8 stream APIs passing TreeSet as Comparator which does natural ordering of string element/objects, as shown in the below syntax
  5. Above step returns Collection<String> using Collectors 
  6. Finally iterate through returned Collection<String> using enhanced forEach loop and print to console

Syntax:

// sort HashSet by converting to TreeSet using Java 8 Stream
		Collection<String> collection = hSetCompanies
				.stream()
				.collect(Collectors.toCollection(TreeSet::new));

SortingHashSetInJava8.java

package in.bench.resources.collection;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class SortingHashSetInJava8 {

	public static void main(String[] args) {

		// creating HashSet object of type String
		Set<String> hSetCompanies =
				new HashSet<String>();


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


		// Iterating using enhanced for-loop
		System.out.println("Random-order: "
				+ "Iterating HashSet\n");
		for(String company : hSetCompanies) {
			System.out.println(company);
		}


		// sort HashSet by converting to TreeSet using Java 8 Stream
		Collection<String> collection = hSetCompanies
				.stream()
				.collect(Collectors.toCollection(TreeSet::new));


		// Iterating using enhanced for-loop
		System.out.println("\n\nAscending Sorting-order: "
				+ "Iterating HashSet\n");
		for(String company : collection) {
			System.out.println(company);
		}
	}
}

Output:

Random-order: Iterating HashSet

LinkedIn
Google
Apple
Microsoft
Amazon
Oracle
Facebook


Ascending Sorting-order: Iterating HashSet

Amazon
Apple
Facebook
Google
LinkedIn
Microsoft
Oracle

1.2 Sorting HashSet with Employee objects

Steps:

  1. First create Employee POJO along with 4-arg parameterized constructor, getter/setter and override toString(); method to print in desired output and compareTo(); method by implementing Comparable interface
  2. Create new HashSet object and add couple of Employee objects to it
  3. Print original HashSet by iterating using enhanced forEach loop introduced in Java 1.5 which will invoke toString() method to print in desired format
  4. Sort using Java 1.8 stream APIs passing class-name as Employee and desired field as getter method of name i.e.; getName() and double-colon (::) separating them, as shown in the below syntax
  5. Above step returns List<Employee> using Collectors 
  6. Finally iterate through returned List<Employee> using enhanced forEach loop and print to console

Syntax:

// sorting using Java 1.8 stream
		List<Employee> lstOfEmployee = hSetEmployees.stream()
		.sorted(Comparator.comparing(
		Employee::getEmpName)) //comparator
		.collect(Collectors.toList()); //collector

Employee.java

package in.bench.resources.collection;

public class Employee implements Comparable<Employee> {

	// employee members
	String empName;
	int empId;
	int empAge;
	String empDesignation;


	// 4-arg parameterized constructor
	public Employee(String empName, int empId,
			int empAge, String empDesignation) {
		super();
		this.empName = empName;
		this.empId = empId;
		this.empAge = empAge;
		this.empDesignation = empDesignation;
	}

	// getters and setters

	// override toString() method
	@Override
	public String toString() {
		return "Employee ["
				+ "empName=" + empName
				+ "\tempId=" + empId
				+ "\tempAge=" + empAge
				+ "\tempDesignation=" + empDesignation
				+ "]";
	}

	// override compareTo() method
	@Override
	public int compareTo(Employee emp) {
		return this.empName.compareTo(emp.getEmpName());
	}
}

SortingHashSetObjectInJava8.java

package in.bench.resources.collection;

import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class SortingHashSetObjectInJava8 {

	public static void main(String[] args) {

		// creating HashSet object of type String
		Set<Employee> hSetEmployees =
				new HashSet<Employee>();


		// creating Employee objects
		Employee employee2 = new Employee(
				"Bill G", 1001, 36, "Consultant");
		Employee employee1 = new Employee(
				"Mark Z", 1002, 30, "Engineer");
		Employee employee4 = new Employee(
				"Sundar P", 1003, 32, "Architect");
		Employee employee3 = new Employee(
				"Larry P", 1004, 25, "Designer");


		// adding Employee to HashSet object
		hSetEmployees.add(employee1);
		hSetEmployees.add(employee2);
		hSetEmployees.add(employee3);
		hSetEmployees.add(employee4);


		// Iterating using enhanced for-loop
		System.out.println("Random-order: "
				+ "Iterating Employee\n");
		hSetEmployees.forEach(
				employee -> System.out.println(employee));


		// sorting using Java 1.8 stream
		List<Employee> lstOfEmployee = hSetEmployees.stream()
				.sorted(Comparator.comparing(
						Employee::getEmpName)) //comparator
				.collect(Collectors.toList()); //collector


		// Iterating using enhanced for-loop
		System.out.println("\n\nAscending Sorting-order: "
				+ "Iterating Employee\n");
		lstOfEmployee.forEach(
				employee -> System.out.println(employee));
	}
}

Output:

Random-order: Iterating Employee

Employee [empName=Sundar P	empId=1003	empAge=32	empDesignation=Architect]
Employee [empName=Bill G	empId=1001	empAge=36	empDesignation=Consultant]
Employee [empName=Larry P	empId=1004	empAge=25	empDesignation=Designer]
Employee [empName=Mark Z	empId=1002	empAge=30	empDesignation=Engineer]


Ascending Sorting-order: Iterating Employee

Employee [empName=Bill G	empId=1001	empAge=36	empDesignation=Consultant]
Employee [empName=Larry P	empId=1004	empAge=25	empDesignation=Designer]
Employee [empName=Mark Z	empId=1002	empAge=30	empDesignation=Engineer]
Employee [empName=Sundar P	empId=1003	empAge=32	empDesignation=Architect]

Related Articles:

Already, we have covered sorting HashSet in different ways prior to Java 1.8 stream APIs, read those article from below links

Happy Coding !!
Happy Learning !!

Java - How to remove elements from LinkedList
Java - How to check whether HashMap is empty or not ?