package ram.com.test;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class SortMapByKey {
public static void main(String[] argv) {
Map
maps.put("z", 34);
maps.put("B", 5);
maps.put("A", 50);
maps.put("c", 43);
maps.put("D", 11);
maps.put("E", 10);
maps.put("Y", 80);
maps.put("N", 99);
System.out.println("Original unsortedMap...");
System.out.println(maps);
// sort by keys, a,b,c..., and return a new LinkedHashMap
// toMap() will returns HashMap by default, we need LinkedHashMap to keep the
// order.
Map
.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println("Sorted by key...");
System.out.println(result);
Map
.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println("Sorted by Value...");
System.out.println(result2);
Map
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println("Sorted by Value in Revers order...");
System.out.println(result3);
}
}
Related Articles
This post first appeared on Java Programming Tutorials Online For Java Coder, please read the originial post: here