Mục lục bài viết

Thủ Thuật về Filter list in Kotlin Chi Tiết

Cập Nhật: 2022-01-05 22:46:08,Bạn Cần tương hỗ về Filter list in Kotlin. Quý quý khách trọn vẹn có thể lại phản hồi ở cuối bài để Ad được tương hỗ.

718

Kotlin List Filter

To filter elements in a Kotlin List based on a predicate (condition), call filter() function on this List and pass the predicate to the filter() function as parameter.

Tóm lược đại ý quan trọng trong bài

  • Kotlin List Filter

In this tutorial, we will learn how to use filter() function on a List, to filter its elements based on a condition/predicate.

The syntax to call filter() function on a List with a predicate is

List.filter(predicate)

predicate is a lambda function that takes an element of the List as parameter and returns a boolean value.

Return Value

List.filter() function returns a List.

Elements of the List that return true for the given predicate, make it to the filtered List.

The original list on which filter() function is called, remains unchanged. Therefore, we can fall filter() function on a List, or a Mutable List.

Examples

In the following program, we will take a List of Integers and filter only even numbers.

Main.kt

fun main(args: Array)
var myList = listOf(1, 4, 8, 5, 6, 9, 12, 10, 33)
var filteredList = myList.filter x -> x % 2 == 0
println(“Original List : $myList”)
println(“Filtered List : $filteredList”)

Here, the lambda function: x -> x % 2 == 0 is the predicate to the filter() function.

For each element x in the List, only those elements that satisfy the condition x % 2 == 0 are returned in the resulting List.

Output

Original List : [1, 4, 8, 5, 6, 9, 12, 10, 33]
Filtered List : [4, 8, 6, 12, 10]

In the following example, we will take a list of Strings, and filter only those strings whose length is greater than 2.

Main.kt

fun main(args: Array)
var myList = listOf(“This”, “is”, “a”, “test”)
var filteredList = myList.filter x -> x.length > 2
println(“Original List : $myList”)
println(“Filtered List : $filteredList”)

Output

Original List : [This, is, a, test]
Filtered List : [This, test]

Conclusion

In this Kotlin Tutorial, we learned how to filter a List using a condition/predicate, using filter() function, with the help of examples.

Reply
4
0
Chia sẻ

đoạn Clip hướng dẫn Share Link Tải Filter list in Kotlin ?

– Một số từ khóa tìm kiếm nhiều : ” Review Filter list in Kotlin tiên tiến và phát triển nhất , Chia Sẻ Link Download Filter list in Kotlin “.

Giải đáp vướng mắc về Filter list in Kotlin

You trọn vẹn có thể để lại Comment nếu gặp yếu tố chưa hiểu nha.
#Filter #list #Kotlin