To filter a map based on values in Kotlin, you can use the `filterValues` method to create a new map containing only the key-value pairs that meet the filter criteria. This method allows you to create a subset of the original map based on specific value conditions.
We can filter a map based on a range of values in Kotlin by using the `filterValues` method to create a new map containing only the key-value pairs that fall within the specified range.
For example,
myMap
with some key-value pairs. In this example, the map has integer keys and integer values.filterValues
method to filter the map based on the specified value range.println
function to verify the filtering.fun main() {
// Declare and initialize a map
val myMap = mapOf(1 to 10, 2 to 20, 3 to 30, 4 to 40, 5 to 50)
// Define the value range
val lowerBound = 20
val upperBound = 40
// Filter the map based on the value range
val filteredMap = myMap.filterValues { it in lowerBound..upperBound }
// Print the filtered map
println("Filtered Map by Value Range: $filteredMap")
}
Filtered Map by Value Range: {2=20, 3=30, 4=40}
We can filter a map based on specific values in Kotlin by using the `filterValues` method to create a new map containing only the key-value pairs that match the specified values.
For example,
myMap
with some key-value pairs. In this example, the map has integer keys and integer values.filterValues
method to filter the map based on the specified values.println
function to verify the filtering.fun main() {
// Declare and initialize a map
val myMap = mapOf(1 to 10, 2 to 20, 3 to 30, 4 to 40, 5 to 50)
// Define the specific values to filter by
val valuesToFilter = setOf(10, 30, 50)
// Filter the map based on the specific values
val filteredMap = myMap.filterValues { it in valuesToFilter }
// Print the filtered map
println("Filtered Map by Specific Values: $filteredMap")
}
Filtered Map by Specific Values: {1=10, 3=30, 5=50}
We can filter a map with string values based on a specific prefix in Kotlin by using the `filterValues` method to create a new map containing only the key-value pairs that have values starting with the given prefix.
For example,
myMap
with some key-value pairs. In this example, the map has integer keys and string values.filterValues
method to filter the map based on the specified prefix.println
function to verify the filtering.fun main() {
// Declare and initialize a map
val myMap = mapOf(1 to "apple", 2 to "banana", 3 to "apricot", 4 to "carrot", 5 to "blueberry")
// Define the prefix to filter by
val prefix = "ap"
// Filter the map based on the prefix
val filteredMap = myMap.filterValues { it.startsWith(prefix) }
// Print the filtered map
println("Filtered Map by Prefix: $filteredMap")
}
Filtered Map by Prefix: {1=apple, 3=apricot}
In this tutorial, we learned How to Filter a Map Based on Values in Kotlin language with well detailed examples.