Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

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.

2. Find an Element in a List

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.

3. Filter Elements in a List

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.

4. Filter Elements in a List with FilterNot

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"))

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.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

Leave a Reply

avatar
  Subscribe  
Notify of