I am working on sorting a map by values code using java 8.
I have done most of the thing but I am not getting how to convert the list to map using java 8 features
public class SortMapByValue {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 3);
map.put("V", 1);
map.put("Anss", 9);
map.put("D", 5);
map.put("E", 2);
map.put("F", 10);
HashMap<String, Integer> newMap = new LinkedHashMap<>();
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue());
// Need to this using Java 8 -- start
for (Entry<String, Integer> entry : list) {
newMap.put(entry.getKey(), entry.getValue());
}
// Need to this using Java 8 -- end
newMap.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));
}
}
Entry::comparingByValue