kotlin-finding-element-in-list
Finding an Element in a List Using Kotlin
1. Overview
2. Find an Element in a List
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.
3. Filter Elements in a 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.
4. Filter Elements in a List with 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"))
5. Conclusion
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.
As usual, all the examples used at this tutorial are available over on GitHub.