How to short a map based on value ?

We can do this in two ways,
By passing a comparator in the map,

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class SortMapByValue {

    public static void main(String[] args) {
        final Map upsortedMap = new HashMap();
        upsortedMap.put("a", "x");
        upsortedMap.put("b", "a");
        upsortedMap.put("c", "z");
        upsortedMap.put("d", "m");
        upsortedMap.put("e", "c");
        Map sortedMap = new TreeMap(new Comparator() {
            public int compare(String s1, String s2) {
                return upsortedMap.get(s1).compareTo(upsortedMap.get(s2));

By using the EntrySet,

No comments:

Post a Comment