- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to sort HashSet in Java
To sort HashSet in Java, you can use another class, which is TreeSet.
Following is the code to sort HashSet in Java −
Example
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
"+ hashSet); Set<String> treeSet = new TreeSet<String>(hashSet); System.out.println("Sorted elements
"+ 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
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
"+ hashSet); List<String> myList = new ArrayList<String>(hashSet); Collections.sort(myList,Collections.reverseOrder()); System.out.println("Sorted (descending order)
"+ myList); } }
Output
HashSet elements [orange, green, blue, yellow, cyan] Sorted (descending order) [yellow, orange, green, cyan, blue]
- Related Articles
- How to create a HashSet in Java?
- HashSet in Java
- Convert array to HashSet in Java
- Add elements to HashSet in Java
- Convert HashSet to TreeSet in Java
- The HashSet in Java
- Initializing HashSet in Java
- Initialize HashSet in Java
- Convert an ArrayList to HashSet in Java
- Importance of HashSet in Java
- Java Program to convert HashSet to Enumeration
- How can we implement a Custom HashSet in Java?
- Get size of HashSet in Java
- Get Enumeration over HashSet in Java
- Traverse through a HashSet in Java

Advertisements