Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin return@forEach from nested forEach

I want to make something like break in the nested forEach loop to filter data in my searchView (if data content contains any word in my search).

val filtered = mutableListOf<EventEntity>()

rawDataList.forEach {data ->
    text.split(' ').forEach { word ->
        if (data.content.contains(word, ignoreCase = true)) {
            filtered.add(data)
            return@forEach // **There is more than one label with such a name in this scope**
        }
    }
}

Does elegant solution exist in my case?

like image 840
caxapexac Avatar asked Nov 10 '19 10:11

caxapexac


2 Answers

If you ever encounter this error and won't be able to fix it with built in function you can apply custom labels to lambdas by adding name@ before the block:

rawDataList.forEach outer@{data ->
    text.split(' ').forEach { word ->
        if (data.content.contains(word, ignoreCase = true)) {
            filtered.add(data)
            return@outer
        }
    }
}
like image 110
Pawel Avatar answered Oct 17 '22 19:10

Pawel


Seems like the any extension method is what you're looking for. From the javadoc:

Returns true if at least one element matches the given [predicate].

val filtered = rawDataList.filter { data ->
    text.split(' ').any { data.content.contains(it, ignoreCase = true) }
}.toMutableList()
like image 24
raven Avatar answered Oct 17 '22 18:10

raven