【问题标题】:Why doesn't hashmap sort correctly? [duplicate]为什么 hashmap 不能正确排序? [复制]
【发布时间】:2019-07-23 11:54:07
【问题描述】:

我想按键排序我的 HashMap。但它无法正确排序。有什么想法吗?

谢谢

我的完整代码

如下:

private static Map<String, Integer> allList = new HashMap<>();
public static String factors(int n) {
    // your code
    for(int i=2;i<n/2;i++){
        getPrimes(n, i);
    }

    Map<String, Integer> result2 = new LinkedHashMap<>();        
    allList.entrySet().stream()
            .sorted(Map.Entry.comparingByKey())
            .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
    String result="";
    for (Map.Entry<String, Integer> entry : result2.entrySet()) {

        if(entry.getValue()>1)
        {
            result = result+"("+entry.getKey()+"**"+entry.getValue()+")";
        }
        else result=result+ "("+entry.getKey()+")";
    }

    return result2;
}

public static Map<String,Integer> getPrimes(int n, int divide)
{
   //part code of put element to allList

}


public static boolean isPrime(int num)
{
        ....
}

当我看起来像下面的结果 2 并且未排序时。

【问题讨论】:

  • 哈希映射未排序,请改用TreeMap
  • Works for me。请使用minimal reproducible example 更新您的问题,以展示问题,并提供完整的代码(包括导入)和输出(作为文本)。
  • 您的屏幕截图显示 allList 而不是 result2。流也应该是无状态的,所以不要在它之外修改地图,让流创建并返回 LinkedHashMap 就像stackoverflow.com/a/15455817
  • 请注意,在对字符串进行排序时,它们被排序为字符串,而不是数字。所以17 出现在2 之前,因为字符1 出现在字符2 之前。
  • 这里有些混乱。您的代码有效,但在调试器中,(Linked)HashMap 列出了它的值仍然是无序的。 LinkedHashMap 是按顺序填充的,因此对其进行迭代也将按顺序进行。当然 String 使排序字母数字,1

标签: java sorting hashmap


【解决方案1】:

您的键是一个字符串,它的排序方式与整数不同。由于提供的信息有限,我认为问题出在那儿。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    相关资源
    最近更新 更多