What is HashMap in java?
- HashMap is Hash table based implementation of the Map interface.
- HashMap provides constant-time performance for the basic operations (get and put).
- HashMap based implementation is not thread safe.
- HashMap must synchronized externally, If multiple threads access a hashmap concurrently.
- Sort the HashMap by keys in ascending & descending order.
- Map<String, String> mapSportsPersonality = new HashMap<>().
- Print the sorted map using forEach method (Java 8)
Program – sort HashMap by keys in ascending & descending order
package org.learn.collection.map.hmap;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class SortElementInArrayList {
public static void main(String[] args) {
Map<String, String> mapSportsPersonality = new HashMap<>();
mapSportsPersonality.put("Tennis", "Federer");
mapSportsPersonality.put("Cricket", "Bradman");
mapSportsPersonality.put("Basketball", "Jordan");
mapSportsPersonality.put("Golf", "Woods");
mapSportsPersonality.put("Boxer", "Ali");
System.out.println("Demo of sort methods: ");
demoSortMethod(mapSportsPersonality);
}
private static void demoSortMethod(Map<String, String> mapSportsPersonality) {
// {Tennis=Federer, Cricket=Bradman, Golf=Woods, Basketball=Jordan, Boxer=Ali}
System.out.println("Orignal HashMap:" + mapSportsPersonality);
System.out.println("\n1. Sort HashMap by ascending keys: " );
TreeMap<String,String>mapSorted = new TreeMap<>(mapSportsPersonality);
mapSorted.forEach((key, value) -> {
System.out.println(key + ", " + value);
});
System.out.println("\n2. Sort HashMap by descending keys: " );
mapSorted.descendingMap().forEach((key, value) -> {
System.out.println( key + ", " + value);
});
}
}
Output – Sort HashMap in ascending & descending order
Demo of sort methods:
Orignal HashMap:{Tennis=Federer, Cricket=Bradman, Golf=Woods, Basketball=Jordan, Boxer=Ali}
1. Sort HashMap by ascending keys:
Basketball, Jordan
Boxer, Ali
Cricket, Bradman
Golf, Woods
Tennis, Federer
2. Sort HashMap by descending keys:
Tennis, Federer
Golf, Woods
Cricket, Bradman
Boxer, Ali
Basketball, Jordan