我需要对 List<String>
进行排序按我的列表 (DESC) 中出现的次数,并从那里删除重复项。我用 Java 编写了这个工作算法:
private List<String> sortByFrequency(List<String> sequence) {
return
sequence.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue(Comparator.reverseOrder())
.thenComparing(Map.Entry.comparingByKey()))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
但它不适用于 Kotlin: kotlin code
因为我得到以下异常:
Type inference failed. Expected type mismatch:
required:
Collector<in String!, Any!, Long!>!
found:
Collector<String!, *, Long!>!
不知道怎么解决。也许你能告诉我吗?
最佳答案
让 Kotlin 为您找出类型。除非需要,否则不要指定类型参数。 Kotlin 会尽力找到正确的类型。
只有一个地方需要指定类型参数,那就是 Map.Entry.comparingByValue
调用。
编译:
fun sortByFrequency(sequence: List<String>): List<String?>? {
return sequence.stream()
.collect(Collectors.groupingBy({ it }, Collectors.counting()))
.entries.stream()
.sorted(
Map.Entry.comparingByValue<String, Long>(Comparator.reverseOrder())
.thenComparing(Map.Entry.comparingByKey())
)
.map { it.key }
.collect(Collectors.toList())
}
但是,代码仍然感觉非常像 Java。 IMO,这是更惯用的 Kotlin:
fun sortByFrequency(sequence: List<String>): List<String> {
val comparator = compareByDescending<Map.Entry<String, Int>> { it.value }
.thenBy { it.key }
return sequence.groupingBy { it }.eachCount().entries
.sortedWith(comparator).map { it.key }
}
注意 groupingBy
的使用和 eachCount
.
关于java - 将 Java 频率排序转换为 Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68678986/