英文:
Using Comparator.thenComparing for passed string
问题
return map.keySet()
.stream()
.sorted(Comparator.comparing(k1 -> map.get(k1)).thenComparing(String::compareTo))
.toArray(String[]::new);
Coc-java
给出了一个错误:The method thenComparing(Comparator<? super Object>) in the type Comparator<Object> is not applicable for the arguments (String::compareTo)
。我之前使用过 thenComparing
,但是 .sorted
方法看起来是这样的:
.sorted(Comparator.comparing(String::length).thenComparing(String::compareTo))
这没有产生错误,正常工作。我猜想这可能与 Lambda 返回的内容有关?
<details>
<summary>英文:</summary>
I'm using streams to try and create an arraylist of the keys in a map sorted first by the values (integers) then sort the keys alphabetically. I have them sorted by the values, but I get an error when trying to compare them alphabetically:
```java
return map.keySet()
.stream()
.sorted(Comparator.comparing( (k1) -> map.get(k1)).thenComparing(String::compareTo)) //ErrorHere
.toArray(String[]::new);
Coc-java gives me a The method thenComparing(Comparator<? super Object>) in the type Comparator<Object> is not applicable for the arguments (String::compareTo)
error. I have used thenComparing before, but the .sorted method looked like this:
.sorted(Comparator.comparing(String::length).thenComparing(String::compareTo))
This produced no errors and worked fine. I'm supposing that it might have something to do with what the lamda returns?
答案1
得分: 1
你可能只需要明确指定类型,例如 Comparator.comparing((String k1) -> map.get(k1))
,或者 Comparator.<String,无论值类型是什么>comparing(map::get)
。
英文:
You probably just need to explicitly specify the type, e.g. Comparator.comparing((String k1) -> map.get(k1))
, or Comparator.<String, WhateverTheValueTypeIs>comparing(map::get)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论