Java – some values are missing when sorting maps by values What causes this strange behavior?

I tried to sort the maps according to word frequency (i.e. based on value) To this end, I have overwritten the comparator and passed it to treemap, but I get this strange output

public class WordFrequency {
    public static String sentence = "one three two two three three four four four";
    public static Map<String,Integer> map;

    public static void main(String[] args) {
        map = new HashMap<>();
        String[] words = sentence.split("\\s");

        for (String word : words) {
            Integer count = map.get(word);
            if (count == null) {
                count = 1;
            } else {
                ++count;
            }
            map.put(word,count);
        }

        Comparator<String> myComparator = new Comparator<String>() {

            @Override
            public int compare(String s1,String s2) {
                if (map.get(s1) < map.get(s2)) {
                    return -1;
                } else if (map.get(s1) > map.get(s2)) {
                    return 1;
                } else {
                    return 0;
                }
            }

        };
        SortedMap<String,Integer> sortedMap = new TreeMap<String,Integer>(myComparator);
        System.out.println("Before sorting: " + map);
        sortedMap.putAll(map);
        System.out.println("After Sorting based on value:" + sortedMap);

    }
}

Output:

Before sorting: {two=2,one=1,three=3,four=3}
After sorting based on value:{one=1,two=2,three=3}

Expected outputs:

{one=1,four=3,three=3}

Solution

Your comparison method cannot follow the Convention of the map interface because it compares values instead of keys Your implementation will cause two keys with the same value to be treated as the same key Therefore, your SortedMap does not contain the "four" key, and its value is the same as the "three" key

TreeMap reference

You can solve this problem by comparing keys when values are equal:

Comparator<String> myComparator = new Comparator<String>() {

        @Override
        public int compare(String s1,String s2) {
            if (map.get(s1) < map.get(s2)) {
                return -1;
            } else if (map.get(s1) > map.get(s2)) {
                return 1;
            } else {
                return s1.compareTo(s2);
            }
        }

    };

This should give you an output:

After sorting based on value:{one=1,three=3}

Since four < three are based on the natural order of strings

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>