How to Sort LinkedHashSet in Java?
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted.
There are three ways to sort LinkedHashSet in Java. Which is the following:
Method 1(Using ArrayList)
In this method, we convert the LinkedHashSet into an ArrayList and then we sort the ArrayList using the sort() method of collections class.
// Convert LinkedHashSet to an ArrayList
ArrayList<Integer> array = new ArrayList<>(set);
// sort ArrayList
Collections.sort(array);
Declaration
public static void sort(List myList)
Parameters: myList is an object we want to sort.
Example:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add( 10 );
set.add( 50 );
set.add( 20 );
set.add( 40 );
set.add( 30 );
System.out.println( "Before sort: " + set);
ArrayList<Integer> array = new ArrayList<>(set);
Collections.sort(array);
System.out.println( "After sort: " + array);
}
}
|
Output
Before sort: [10, 50, 20, 40, 30]
After sort: [10, 20, 30, 40, 50]
Method 2: Using TreeSet
In this method, we convert LinkedHashSet to a TreeSet using the constructor to automatically sort the elements.
// Convert LinkedHashSet to a TreeSet
TreeSet<Integer> tree_set = new TreeSet<>(set);
Example:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add( 10 );
set.add( 50 );
set.add( 20 );
set.add( 40 );
set.add( 30 );
System.out.println( "Before sort: " + set);
TreeSet<Integer> tree_set = new TreeSet<>(set);
System.out.println( "After sort: " + tree_set);
}
}
|
Output
Before sort: [10, 50, 20, 40, 30]
After sort: [10, 20, 30, 40, 50]
Method 3: Using stream
In this method, we sort the LinkedHashSet using stream and sorted() function of the stream.
// Sort and print using stream
set.stream().sorted().forEach(System.out::println);
Below is the implementation:
Example:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add( 10 );
set.add( 50 );
set.add( 20 );
set.add( 40 );
set.add( 30 );
System.out.println( "Before sort: " + set);
System.out.println( "After sort: " );
set.stream().sorted().forEach(System.out::println);
}
}
|
Output
Before sort: [10, 50, 20, 40, 30]
After sort:
10
20
30
40
50
Last Updated :
04 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...