
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
In this tutorial, we’re going to see how to find an element in a list using Kotlin language. Also, we’re going to filter this list by a condition.
Let’s say that we have a list of actors that have performed as Batman:
var batmans: List<String> = listOf("Christian Bale", "Michael Keaton", "Ben Affleck", "George Clooney")
And let’s say that we want to find “the first Batman” (from the Tim Burton movie) – Michael Keaton.
In Kotlin we can use find in order to return the first element matching the given predicate:
val theFirstBatman = batmans.find { actor -> "Michael Keaton".equals(actor) }
assertEquals(theFirstBatman, "Michael Keaton")
However, if no such element is found the find will return null.
On the other hand, we’re going to filter the batmans list.
We want to just keep the coolest Batman actors. Again, that would be Michael Keaton, the original, and the one from Nolan’s Trilogy, Christian Bale.
In that case, let’s use the filter function and a predicate to get the list containing the coolest Batmans:
val theCoolestBatmans = batmans.filter { actor -> actor.contains("a") }
assertTrue(theCoolestBatmans.contains("Christian Bale") &&
theCoolestBatmans.contains("Michael Keaton"))
Or, we’ll get an empty list if no such element matches the predicate.
Also, we can use an inverse filter using filterNot:
val theMehBatmans = batmans.filterNot { actor -> actor.contains("a") }
assertFalse(theMehBatmans.contains("Christian Bale") &&
theMehBatmans.contains("Michael Keaton"))
assertTrue(theMehBatmans.contains("Ben Affleck") &&
theMehBatmans.contains("George Clooney"))
In this tutorial, we’ve looked at how easy is to use Kotlin with lists to find and filter elements on it.
We can find more detailed info in Kotlin’s official find documentation, filter documentation, and filterNot documentation.