我试图按值排序HashMap,但我得到的结果非常尴尬。任何人都可以帮我确定原因

时间:2015-10-17 20:01:53

标签: java hashmap treemap sortedmap

这是按值对HashMap进行排序的代码。

public class LongestChain
{
public static void main(String[] args)
{
    String words[] = new String[]{"a","b", "c", "ca","ba","bca","bda","bdca"};
    System.out.println(longestChainOfWords(words));
}

public static int longestChainOfWords(String words[])
{
    Map<String, Integer> map = new HashMap<String, Integer>();

    for(String a:words)
    {
        map.put(a, a.length());
    }

    System.out.println(map);

    Map sortedMap = sortByValue(map);
    System.out.println(sortedMap);



    return sortedMap.size();
}

public static Map<String, Integer> sortByValue(Map<String, Integer> unsortedMap) 
{
    Map<String, Integer> sortedMap = new TreeMap<String, Integer>(new ValueComparator(unsortedMap));
    sortedMap.putAll(unsortedMap);
    return sortedMap;
}

}

class ValueComparator implements Comparator 
{
    Map<String, Integer> map;

    public ValueComparator(Map<String, Integer> map)
    {
        this.map = map;
    }

    public int compare(Object keyA, Object keyB)
    {
        Comparable valueA = map.get(keyA);
        Comparable valueB = map.get(keyB);
        System.out.println(keyA+" keyA "); System.out.println(keyB+" keyB ");
        return valueA.compareTo(valueB);
    }

}

输出是这样的。我也期待sortedMap中的8个元素。为什么行为是这样的?

{ca = 2,bda = 3,ba = 2,b = 1,c = 1,a = 1,bdca = 4,bca = 3} {b = 1,ca = 2,bda = 3,bdca = 4} 4

1 个答案:

答案 0 :(得分:0)

因为你让TreeMap认为它对键进行排序。如果密钥相等,则不会将新值放入其中。由于您有4个不同的值,因此您可以在列表中找到4个结果。

您可以做的是改进比较方法,以便按键排序相同的值:

while num>1:    
    for i in range(2,num+1):  # start range with 2
        if num%i==0:    
            num=num//i  
            if num%i==0: 
                num=num//i
                numbers.append(i)
            else:
                roots.append(i)
            break  # increase indent on this line by two levels!