You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Stream替代循环在Kotlin列表中查找指定元素

问题描述

我有一个列表:

val tidslinjehendelser = kontaktPage.tidslinjeCard().getTidslinjehendelser()

fun getTidslinjehendelser(): MutableList<TidslinjehendelseElement> {
    return Getters.getElementsInElement(element, By.tagName("tidslinje-hendelse")).stream()
        .map { el: WebElement? -> TidslinjehendelseElement(el) }.collect(Collectors.toList())
}

列表元素是TidslinjehendelseElement类的实例:

class TidslinjehendelseElement(private val element: WebElement?) {
    fun dato(): String {
        return getElementInElement(element, By.cssSelector("[data-e2e-selector=tidslinje-hendelse-dato]")).text
    }
    
    fun navn(): String { return getElementInElement(element, By.className("hendelse-navn")).text }
    
    fun innhold(): String { return getElementInElement(element, By.className("hendelse-body")).text }
}

我需要查找其中innhold()返回文本包含指定字符串melding的元素,目前用循环实现:

for (hendelse in tidslinjehendelser) {
    if (hendelse.innhold().contains(melding)) {
        print("yay!")
    }
}

希望改用Stream流替代循环完成该操作。

解决方案

1. 匹配首个元素并执行操作

通过stream()将列表转为流,用*filter()筛选出符合条件的元素,再用findFirst()获取第一个匹配项,最后用ifPresent()*执行打印:

tidslinjehendelser.stream()
    .filter { it.innhold().contains(melding) }
    .findFirst()
    .ifPresent { print("yay!") }

2. 处理所有匹配元素

如果需要对所有符合条件的元素执行打印操作,用*forEach()*遍历筛选后的流:

tidslinjehendelser.stream()
    .filter { it.innhold().contains(melding) }
    .forEach { print("yay!") }

3. 收集所有匹配元素到新列表

若需要保存匹配元素供后续使用,用*collect()*将筛选结果收集为新列表:

val matchingElements = tidslinjehendelser.stream()
    .filter { it.innhold().contains(melding) }
    .collect(Collectors.toList())

// 后续操作示例
matchingElements.forEach { print("yay!") }

Kotlin原生简化写法

因为你使用的是Kotlin,也可以用它原生的集合操作,语法更简洁:

// 匹配首个元素并执行操作
tidslinjehendelser.firstOrNull { it.innhold().contains(melding) }?.let { print("yay!") }

// 处理所有匹配元素
tidslinjehendelser.filter { it.innhold().contains(melding) }.forEach { print("yay!") }

// 收集所有匹配元素
val matchingElements = tidslinjehendelser.filter { it.innhold().contains(melding) }

内容的提问来源于stack exchange,提问作者kakemonsteret

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 21:05:20