首页 > 解决方案 > 如果在 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())

我正在做的任何替代方案将不胜感激。

标签: kotlinarraylist

解决方案


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
}

推荐阅读