Search code examples
javakotlinjava-stream

Kotlin or Java: Using stream() to find element in list


I have the following list:

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())
}

Which is created from this class:

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 }
}

What I want to do, is to search for an element where the innhold() text contains a certain text string.

Right now, I'm doing it with a loop:

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

But since I've just started looking at streams, I'd like to explore using that method instead of the looping method.


Solution

  • You can use streams to filter the tidslinjehendelser list to get only the elements whose innhold() method returns a string containing a certain text string. Here's an example:

    tidslinjehendelser.stream()
    .filter { hendelse -> hendelse.innhold().contains(melding) }
    .forEach { hendelse -> println("yay!") }
    

    This code uses the stream() method to convert the tidslinjehendelser list to a stream. Then, it uses the filter() method to filter the stream and keep only the elements whose innhold() method returns a string containing the melding text. Finally, it uses the forEach() method to loop over the filtered stream and print "yay!" for each matching element.

    You can replace the println("yay!") statement with any other code you want to execute for the matching elements. Also note that this code will stop iterating over the stream once it finds the first matching element. If you want to find all the matching elements, you can use the collect() method instead of forEach() to collect the matching elements into a new list or other collection.