首页 > 解决方案 > 如何使用 Kotlin 进行特定排序?

问题描述

我在 Kotlin 中有这个 ArrayList :

a = ArrayList<String>()
a.add("eat")
a.add("animal")
a.add("internet")

我想按“e”的频率对我的 ArrayList 的元素进行排序,例如我想要一个新的 ArrayList,例如:

a[0] = "animal" // there is no e in animal
a[1] = "eat" // there is one e in animal
a[2] = "internet" // there is two e in internet

我想使用 Collections.sort(a) 但就像我的排序是特定的那样它不会工作......

你有什么想法 ?

谢谢 !

标签: kotlin

解决方案


您也可以在不将每个转换StringCharArray第一个(如当前接受的答案中)的情况下执行此操作,我不知道您为什么要这样做:

a.sortBy { it.count { it == 'e' } }

另外,您可能想要命名嵌套it的 s:

a.sortBy { word -> word.count { character -> character == 'e' } }

推荐阅读