kotlin - 如果在 Kotlin 中已经包含以 `it` 开头的字符串,则 ArrayList 删除
问题描述
我有这样ArrayList<String>
的数据:
download
download name:string
download name:string url:string
download test:string
list
print
print name:string
reload
reload name:string
示例输出应如下所示:
download name:string url:string
download test:string // note this one does not get filtered
list
print name:string
reload name:string
但我想删除download
因为download name:string
存在,也想删除download name:string
因为download name:string url:string
存在。
我尝试使用两个数组列表和一堆过滤器,但它变得非常混乱,我提出的解决方案导致了一个空的数组列表。
我试过的例子:
val subCommands1 = arrayListOf<String>()
subCommands
.stream()
.sorted(Comparator.comparingInt(String::length))
.filter {
var found = false
subCommands1
.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList())
.reversed()
.forEach { comIt ->
if (comIt.startsWith(it)) {
found = true
}
}
if (!found) {
subCommands1.add(it)
}
!found
}
.collect(Collectors.toList())
我正在做的任何替代方案将不胜感激。
解决方案
fun filterSubCommands(list: List<String>): List<String> {
if (list.size < 2) return ArrayList(list)
val result = ArrayList<String>()
list.asSequence().sorted().zipWithNext().forEach { (a, b) ->
if (!b.startsWith(a)) result.add(a)
}
result.add(list.last())
return result
}
推荐阅读
- c# - 无法将字符串“名称”转换为字典键类型 - 创建一个 TypeConverter 以从字符串转换为键类型对象
- kubernetes - Spinnaker 中存储设置的自定义配置文件
- python - How does this while-loop compute? (x = function(x))
- keras - 如何在谷歌 colab 中找到 keras.json 文件?
- node.js - 将 Strapi API 部署到 Plesk
- java - X509TrustManager 的 checkServerTrusted 方法中验证了哪些所有参数?
- python - 在 python 的子目录中对具有字母数字字符的列表作为文件名进行排序
- objective-c - VSCode 显示 Objective-C 头文件的“无法识别的令牌”
- sql-server - 将 SQL Server 2016 兼容级别更改为 2012
- angular - ngI18nClosureMode 未定义