Java 8 – How to sort LinkedHashSet using Stream

In this article, we will discuss how to sort LinkedHashSet elements in ascending & descending order using Java 8

Before proceeding with this sorting examples understand below items,

1. Stream.sorted() method

  • This Stream method is an stateful intermediate operation which sorts elements present in the stream according to natural order
  • If elements present in the stream aren’t Comparable then java.lang.ClassCastException is thrown when final terminal operation is executed
  • For ordered streams, the sort is stable
  • For unordered streams, no stability guarantees are made
  • Method signature 1 :- Stream<T> sorted()
  • Method signature 2 :- Stream<T> sorted(Comparator<? super T> comparator)

1.1 Sorting LinkedHashSet of Integer numbers

  • A LinkedHashSet contains integer numbers in insertion-order
  • We are sorting these integer numbers in natural order and descending order using Java 8 Stream’s sorted() method

SortLinkedHashSetOfIntegerUsingStream.java

package net.bench.resources.sort.linkedhashset;

import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.Set;

public class SortLinkedHashSetOfIntegerUsingStream {

	public static void main(String[] args) {

		// 1. create LinkedHashSet
		Set<Integer> numbers = new LinkedHashSet<>();


		// 1.2 add integer numbers to LHS
		numbers.add(81);
		numbers.add(21);
		numbers.add(91);
		numbers.add(61);
		numbers.add(31);
		numbers.add(71);
		numbers.add(51);


		// 1.3 original LinkedHashSet in insertion order
		System.out.println("1. Original LinkedHashSet<Integer> "
				+ "as per insertion-order :- \n");
		numbers.forEach(System.out::println);


		// 2. Natural order
		System.out.println("\n2. Natural order of "
				+ "LinkedHashSet<Integer> :- \n");


		// 2.1 natural order - Stream.sorted() and print
		numbers
		.stream() // get sequential stream
		.sorted() // natural order sorting
		.forEach(System.out::println); // print


		// 3. Reverse Order
		System.out.println("\n3. Reverse order of "
				+ "LinkedHashSet<Integer> :- \n");


		// 3.1 reverse order - Stream.sorted() and print
		numbers
		.stream() // get sequential stream
		.sorted(Comparator.reverseOrder()) // reverse order sorting
		.forEach(System.out::println); // print
	}
}

Output:

1. Original LinkedHashSet<Integer> as per insertion-order :- 

81
21
91
61
31
71
51

2. Natural order of LinkedHashSet<Integer> :- 

21
31
51
61
71
81
91

3. Reverse order of LinkedHashSet<Integer> :- 

91
81
71
61
51
31
21

1.2 Sorting LinkedHashSet of String elements

  • A LinkedHashSet contains String elements in insertion-order
  • We are sorting these String elements in alphabetical order using Java 8 Stream’s sorted() method

SortLinkedHashSetOfStringUsingStream.java

package net.bench.resources.sort.linkedhashset;

import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.Set;

public class SortLinkedHashSetOfStringUsingStream {

	public static void main(String[] args) {

		// 1. create LinkedHashSet
		Set<String> names = new LinkedHashSet<>();


		// 1.1 add names to LHS
		names.add("Saranya");
		names.add("Karthika");
		names.add("Amudha");
		names.add("Pushpa");
		names.add("Bhagyalakshmi");
		names.add("Meena");


		// 1.2 original LinkedHashSet in insertion order
		System.out.println("1. Original LinkedHashSet<String> "
				+ "as per insertion-order :- \n");
		names.forEach(System.out::println);


		// 2. Sorting Alphabetical order
		System.out.println("\n2. Alphabetically sorted-order "
				+ "of LinkedHashSet<String> :- \n");


		// 2.1 sort using Stream - alphabetical order
		names
		.stream() // get sequential stream
		.sorted() // alphabetical sorting
		.forEach(System.out::println); // print


		// 3. Sorting Reverse Alphabetical order
		System.out.println("\n3. Reverse alphabetically sorted-order "
				+ "of LinkedHashSet<String> :- \n");


		// 3.1 sort using Stream - reverse alphabetical order
		names
		.stream() // get sequential stream
		.sorted(Comparator.reverseOrder()) // reverse alphabetical sorting
		.forEach(System.out::println); // print
	}
}

Output:

1. Original LinkedHashSet<String> as per insertion-order :- 

Saranya
Karthika
Amudha
Pushpa
Bhagyalakshmi
Meena

2. Alphabetically sorted-order of LinkedHashSet<String> :- 

Amudha
Bhagyalakshmi
Karthika
Meena
Pushpa
Saranya

3. Reverse alphabetically sorted-order of LinkedHashSet<String> :- 

Saranya
Pushpa
Meena
Karthika
Bhagyalakshmi
Amudha

1.3 Sorting LinkedHashSet of Employee objects

  • A LinkedHashSet contains Employee objects with attributes such as Id, name and their salary in insertion-order
  • We are sorting these Employee objects according to their salary in natural order and their Id in descending order using Java 8 Stream’s sorted() method

Employee.java

package net.bench.resources.sort.linkedhashset;

public class Employee {

	// member variables
	private int id;
	private String name;
	private long salary;

	// 3-arg parameterized constructor

	// getters and setters

	// toString()
}

SortLinkedHashSetOfEmployeesUsingStreamSorted.java

package net.bench.resources.sort.linkedhashset;

import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.Set;

public class SortLinkedHashSetOfEmployeesUsingStreamSorted {

	public static void main(String[] args) {

		// 1. create LinkedHashSet
		Set<Employee> employees = new LinkedHashSet<>();


		// 1.1 add Employees to LHS
		employees.add(new Employee(101, "Saranya", 85000L));
		employees.add(new Employee(102, "ThenMozhi", 57000L));
		employees.add(new Employee(103, "Amudha", 49000L));
		employees.add(new Employee(104, "Pushpa", 24000L));
		employees.add(new Employee(105, "Bhagyalakshmi", 29000L));
		employees.add(new Employee(106, "Meena", 38000L));


		// 1.2 original LinkedHashSet in insertion order
		System.out.println("1. Original LinkedHashSet "
				+ "as per insertion-order :- \n");
		employees.forEach(System.out::println);


		// 2. Sorting Employee - increasing salary
		System.out.println("\n2. Sorted Employee LinkedHashSet -"
				+ " according to increasing salary :- \n");


		// 2.1 sort using Stream - increasing-order of salary
		employees
		.stream()
		.sorted(Comparator.comparingLong(Employee::getSalary))
		.forEach(System.out::println);


		// 3. Sorting Employee - increasing salary
		System.out.println("\n3. Reverse sorted Employee LinkedHashSet -"
				+ " according to descending Id :- \n");


		// 3.1 sort using Stream - reverse-order of employee Id
		employees
		.stream()
		.sorted(Comparator.comparingInt(Employee::getId).reversed())
		.forEach(System.out::println);
	}
}

Output:

1. Original LinkedHashSet as per insertion-order :- 

Employee [id=101, name=Saranya, salary=85000]
Employee [id=102, name=ThenMozhi, salary=57000]
Employee [id=103, name=Amudha, salary=49000]
Employee [id=104, name=Pushpa, salary=24000]
Employee [id=105, name=Bhagyalakshmi, salary=29000]
Employee [id=106, name=Meena, salary=38000]

2. Sorted Employee LinkedHashSet - according to increasing salary :- 

Employee [id=104, name=Pushpa, salary=24000]
Employee [id=105, name=Bhagyalakshmi, salary=29000]
Employee [id=106, name=Meena, salary=38000]
Employee [id=103, name=Amudha, salary=49000]
Employee [id=102, name=ThenMozhi, salary=57000]
Employee [id=101, name=Saranya, salary=85000]

3. Reverse sorted Employee LinkedHashSet - according to descending Id :- 

Employee [id=106, name=Meena, salary=38000]
Employee [id=105, name=Bhagyalakshmi, salary=29000]
Employee [id=104, name=Pushpa, salary=24000]
Employee [id=103, name=Amudha, salary=49000]
Employee [id=102, name=ThenMozhi, salary=57000]
Employee [id=101, name=Saranya, salary=85000]

2. Other approaches

  1. We can use TreeSet class & Comparator to sort LinkedHashSet contents in ascending/descending order
  2. Convert the given LinkedHashSet contents into a List first and sort using Collections‘ class sort() method

2.1 Sorting LinkedHashSet using TreeSet/Comparator

  • A LinkedHashSet contains String elements in insertion-order
  • We are sorting these String elements in natural order (or ascending order) using TreeSet/Comparator

SortLinkedHashSetOfStringUsingTreeSet.java

package net.bench.resources.sort.linkedhashset;

import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class SortLinkedHashSetOfStringUsingTreeSet {

	public static void main(String[] args) {

		// 1. create LinkedHashSet
		Set<String> names = new LinkedHashSet<>();


		// 1.1 add names to LHS
		names.add("Saranya");
		names.add("Karthika");
		names.add("Amudha");
		names.add("Pushpa");
		names.add("Bhagyalakshmi");
		names.add("Meena");


		// 1.2 original LinkedHashSet in insertion order
		System.out.println("1. Original LinkedHashSet<String> "
				+ "as per insertion-order :- \n");
		names.forEach(System.out::println);


		// 2. Sorting Alphabetical order
		System.out.println("\n2. Alphabetically sorted-order "
				+ "of LinkedHashSet<String> :- \n");


		// 2.1 sort using TreeSet - alphabetical order
		TreeSet<String> treeSet1 = new TreeSet<String>(names);
		treeSet1.forEach(System.out::println);


		// 3. Sorting Reverse Alphabetical order
		System.out.println("\n3. Reverse alphabetically sorted-order "
				+ "of LinkedHashSet<String> :- \n");


		// 3.1 sort using TreeSet/Comparator.reverseOrder()
		TreeSet<String> treeSet2 = new TreeSet<String>(Comparator.reverseOrder());
		treeSet2.addAll(names);
		treeSet2.forEach(System.out::println);
	}
}

Output:

1. Original LinkedHashSet<String> as per insertion-order :- 

Saranya
Karthika
Amudha
Pushpa
Bhagyalakshmi
Meena

2. Alphabetically sorted-order of LinkedHashSet<String> :- 

Amudha
Bhagyalakshmi
Karthika
Meena
Pushpa
Saranya

3. Reverse alphabetically sorted-order of LinkedHashSet<String> :- 

Saranya
Pushpa
Meena
Karthika
Bhagyalakshmi
Amudha

2.2 Sorting LinkedHashSet using Collections.sort() method

  • A LinkedHashSet contains String elements in insertion-order
  • We are sorting these String elements in natural order (or ascending order) using Collections.sort() method

SortArrayListOfIntegerUsingListSortMethod.java

package net.bench.resources.sort.linkedhashset;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class SortLinkedHashSetOfStringUsingCollectionsSort {

	public static void main(String[] args) {

		// 1. create LinkedHashSet
		Set<String> names = new LinkedHashSet<>();


		// 1.1 add names to LHS
		names.add("Saranya");
		names.add("Karthika");
		names.add("Amudha");
		names.add("Pushpa");
		names.add("Bhagyalakshmi");
		names.add("Meena");


		// 1.2 original LinkedHashSet in insertion order
		System.out.println("1. Original LinkedHashSet<String> "
				+ "as per insertion-order :- \n");
		names.forEach(System.out::println);


		// 1.3 convert LinkedHashSet to List
		List<String> list = new ArrayList<String>(names);


		// 2. Sorting Alphabetical order
		System.out.println("\n2. Alphabetically sorted-order "
				+ "of LinkedHashSet<String> :- \n");


		// 2.1 alphabetical order sorting using Collections.sort()
		Collections.sort(list); // natural order
		list.forEach(System.out::println);


		// 3. Sorting Reverse Alphabetical order
		System.out.println("\n3. Reverse alphabetically sorted-order "
				+ "of LinkedHashSet<String> :- \n");


		// 3.1 Reverse alphabetical order sorting 
		// using Collections.sort() and Comparator.reverseOrder()
		Collections.sort(list, Comparator.reverseOrder()); // reverse order
		list.forEach(System.out::println);
	}
}

Output:

1. Original LinkedHashSet<String> as per insertion-order :- 

Saranya
Karthika
Amudha
Pushpa
Bhagyalakshmi
Meena

2. Alphabetically sorted-order of LinkedHashSet<String> :- 

Amudha
Bhagyalakshmi
Karthika
Meena
Pushpa
Saranya

3. Reverse alphabetically sorted-order of LinkedHashSet<String> :- 

Saranya
Pushpa
Meena
Karthika
Bhagyalakshmi
Amudha

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to sort TreeSet in descending order using Stream
Java 8 – How to sort LinkedList using Stream