使用 Comparator.thenComparing 对传递的字符串排序。

huangapple go评论72阅读模式
英文:

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&#39;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) -&gt; map.get(k1)).thenComparing(String::compareTo)) //ErrorHere
          .toArray(String[]::new);

Coc-java gives me a The method thenComparing(Comparator&lt;? super Object&gt;) in the type Comparator&lt;Object&gt; 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) -&gt; map.get(k1)), or Comparator.&lt;String, WhateverTheValueTypeIs&gt;comparing(map::get).

huangapple
  • 本文由 发表于 2020年10月20日 07:16:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64436304.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定