kotlin - 如何使用 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) 但就像我的排序是特定的那样它不会工作......
你有什么想法 ?
谢谢 !
解决方案
您也可以在不将每个转换String
为CharArray
第一个(如当前接受的答案中)的情况下执行此操作,我不知道您为什么要这样做:
a.sortBy { it.count { it == 'e' } }
另外,您可能想要命名嵌套it
的 s:
a.sortBy { word -> word.count { character -> character == 'e' } }
推荐阅读
- java - Java:是否可以在没有反射的情况下反序列化对象
- python - Python如何捕获检测到的二维码?
- excel - 如何将日期单元格(独立于语言环境)连接到 Excel 中的字符串?
- reactjs - React:如何通过 Firestore onSnapshot 和 useEffect 使用最新状态?
- .net-core - .Net Standard 2.0 和 .Net Framework 4.6.1 与 4.7.2
- matlab - 将 0 和 1 的 char 向量拆分为加倍
- linux - Docker 容器未启动
- python - 数据操作,一种下采样
- android - 创建 AppBarIcon 图像
- flutter - 是否可以将对象传递给上下文?