Sort HashMap in Java 8

Sanjay Singh
Dec 27, 2020

import java.util.Comparator;

import java.util.HashMap;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.stream.Collectors;

public class ExampleOfMapInJava8 {

public static <T> void main(String[] args) {

Map<String, Integer> map = new HashMap<String, Integer>();

map.put(“RAJ”, 40);

map.put(“TAJ”, 90);

map.put(“BAJ”, 30);

map.put(“AAJ”, 460);

map.put(“GAJ”, 401);

map.put(“LKK”, 240);

Map result =map.entrySet().stream().sorted(Map.Entry.comparingByKey())

.collect(Collectors.toMap(Map.Entry::getKey,

Map.Entry::getValue, (oldKey, newKey) -> oldKey, LinkedHashMap::new));

Map value = map.entrySet().stream().sorted(Map.Entry.comparingByValue())

.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue ,

(oldValue, newValue) -> oldValue, LinkedHashMap::new))

;

// Reverse Order

Map revValue = map.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))

.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue ,

(oldValue, newValue) -> oldValue, LinkedHashMap::new))

;

System.out.println(value);

}

}

--

--

Sanjay Singh

Java||Spring-Boot|| Micro services Application developer|| INDIA