package com.sandbox.code;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class HashMapKeySort {
public static void main(String[] args) {
Map<String, Integer> mapVal = new HashMap<>();
mapVal.put("Sam", 42);
mapVal.put("Adam", 43);
mapVal.put("Chandler", 18);
mapVal.put("Bob", 50);
mapVal.put("Micheal", 16);
mapVal = new HashMapKeySort().sortedMap(mapVal);
mapVal.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));
}
public Map<String, Integer> sortedMap(Map<String, Integer> map) {
return map.entrySet().stream().sorted(Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (k, v) -> k, LinkedHashMap::new));
}
}
0 Comments