How to sort HashSet in Java

Java 8Object Oriented ProgrammingProgramming

To sort HashSet in Java, you can use another class, which is TreeSet.

Following is the code to sort HashSet in Java −

Example

 Live Demo

import java.util.*;
public class Main {
   public static void main(String args[]) {
      Set<String> hashSet = new HashSet<String>();
      hashSet.add("green");
      hashSet.add("blue");
      hashSet.add("red");
      hashSet.add("cyan");
      hashSet.add("orange");
      hashSet.add("green");
      System.out.println("HashSet elements\n"+ hashSet);
      Set<String> treeSet = new TreeSet<String>(hashSet);
      System.out.println("Sorted elements\n"+ treeSet);
   }
}

Output

HashSet elements
[red, orange, green, blue, cyan]
Sorted elements
[blue, cyan, green, orange, red]

Let us see another example wherein we will sort the HashSet in descending order using Collections.sort() method with reverseOrder() method −

Example

 Live Demo

import java.util.*;
public class Main {
   public static void main(String args[]) {
      Set<String> hashSet = new HashSet<String>();
      hashSet.add("yellow");
      hashSet.add("green");
      hashSet.add("blue");
      hashSet.add("cyan");
      hashSet.add("orange");
      hashSet.add("green");
      System.out.println("HashSet elements\n"+ hashSet);
      List<String> myList = new ArrayList<String>(hashSet);
      Collections.sort(myList,Collections.reverseOrder());
      System.out.println("Sorted (descending order)\n"+ myList);
   }
}

Output

HashSet elements
[orange, green, blue, yellow, cyan]
Sorted (descending order)
[yellow, orange, green, cyan, blue]
raja
Published on 20-Sep-2019 10:44:36
Advertisements