Sorting by Values using TreeSet
We can sort a HashMap by values using a TreeSet. A TreeSet also stores data in sorted order(sorted by values). Follow the code below:
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeSet;
public class HashMapSortDemo {
public static void main(String args[]) {
HashMap<String, Integer> unsortedMap = new HashMap<>();
unsortedMap.put("one", 1);
unsortedMap.put("two", 2);
unsortedMap.put("three", 3);
unsortedMap.put("four", 4);
unsortedMap.put("five", 5);
unsortedMap.put("fourteen", 4);
unsortedMap.put("fifteen", 5);
unsortedMap.put("twenty", 2);
System.out.println("Printing the Unsorted HashMap");
for(Entry<String, Integer> e : unsortedMap.entrySet()) {
System.out.println(e.getKey() + "-->" + e.getValue());
}
TreeSet<Integer> sortedSet = new TreeSet<>(unsortedMap.values());
System.out.println("\nThe sorted values are: " + sortedSet);
}
}
The code above is sorting the HashMap by values using a TreeSet.
Use the following command to compile and run the code:
javac HashMapSortDemo.java && java HashMapSortDemo