In this tutorial, you shall learn how to filter list of strings based on string length in Kotlin using List.filter() function, with examples.
Kotlin String List – Filter based on Length
To filter String elements of a Kotlin List based on String length, call filter() function on this String List and pass the required condition as predicate to the filter() function as parameter.
In this tutorial, we will learn how to use filter() function on a List of Strings, and filter the elements based on String length.
Examples
1. Filter strings in given list whose length is greater than 2
In the following program, we will take a List of Strings and filter only those strings whose length is greater than 2.
Main.kt
fun main(args: Array<String>) {
var myList = listOf("This", "is" ,"a", "sample", "message", ".")
var filteredList = myList.filter { x -> x.length > 2 }
println("Original List : ${myList}")
println("Filtered List : ${filteredList}")
}
Here, the lambda function: { x -> x.length > 2 }
is the predicate to the filter() function. This predicate returns true
if the length of the String x
is greater than 2, or false
if length of String x
is not greater than 2.
For each element x
in the List, only those elements that satisfy the condition x.length > 2
are returned in the resulting List.
Output
Original List : [This, is, a, sample, message, .]
Filtered List : [This, sample, message]
2. Filter strings in given list whose length is equal to 4
Now, let us filter only those strings whose length is only 4.
Main.kt
fun main(args: Array<String>) {
var myList = listOf("abcd", "is" ,"four", "letter", "word", ".")
var filteredList = myList.filter { x -> x.length == 4 }
println("Original List : ${myList}")
println("Filtered List : ${filteredList}")
}
Output
Original List : [abcd, is, four, letter, word, .]
Filtered List : [abcd, four, word]
Only those String elements that has a length of 4 made it to the filtered list.
Conclusion
In this Kotlin Tutorial, we learned how to filter a List of Strings using filter() function based on String length, with the help of examples.