Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to sort map using key and value in java


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 = new HashMap();
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 result = maps.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors
.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

System.out.println("Sorted by key...");
System.out.println(result);

Map result2 = maps.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors
.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

System.out.println("Sorted by Value...");
System.out.println(result2);

Map result3 = maps.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("Sorted by Value in Revers order...");
System.out.println(result3);

}

}



This post first appeared on Java Programming Tutorials Online For Java Coder, please read the originial post: here

Share the post

How to sort map using key and value in java

×

Subscribe to Java Programming Tutorials Online For Java Coder

Get updates delivered right to your inbox!

Thank you for your subscription

×