【问题标题】:Sorting Map with Comparator causing syntax error使用 Comparator 对 Map 进行排序导致语法错误
【发布时间】:2015-11-26 20:10:31
【问题描述】:

我正在尝试像这样对地图进行排序(首先按值(整数)然后按键(字符串))

public static Map<String, Integer> sortMap(Map<String, Integer> map) {
    List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet()); 
    // thenComparing( ... ) is causing an error
    list.sort(Map.Entry.comparingByValue().thenComparing(Map.Entry.comparingByKey()));   

    //...
}

我收到以下错误:

知道我错过了什么吗?在我的previous question 中建议将其作为替代方案,但我无法使其工作。

【问题讨论】:

  • @Reimeus "java -version" in cmd 给了我 "1.8.0_51",我不完全确定 Java 8 是什么意思。我的项目语言级别设置为 8。Here 是我的 intellij idea 设置的截图。

标签: java sorting dictionary


【解决方案1】:

不幸的是类型推断在这里失败了,你必须给它泛型类型。

list.sort(Map.Entry.<String,Integer>comparingByValue()
        .thenComparing(Map.Entry.comparingByKey()));

【讨论】:

  • @Shiro 我发现类型推断可能意味着从解决错误到错误的解决方案可能需要很长的路要走。当 Java 更加冗长时,一切都更加具体,并且您会遇到更接近问题原因的错误。类型推断很棒,但没有实体的错误消息是它的阴暗面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-08
相关资源
最近更新 更多