Bird
0
0

Given a map with nullable values: val map: Map = mapOf("a" to "apple", "b" to null, "c" to "cat") How do you create a new map excluding entries with null values using Kotlin?

hard📝 Application Q9 of 15
Kotlin - Null Safety
Given a map with nullable values: val map: Map = mapOf("a" to "apple", "b" to null, "c" to "cat") How do you create a new map excluding entries with null values using Kotlin?
Aval filtered = map.filter { it.value == null }
Bval filtered = map.filterValues { it != null }
Cval filtered = map.mapValues { it.value!! }
Dval filtered = map.filterKeys { it != null }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the map and filtering goal

    The map has nullable values. We want to exclude entries where the value is null.
  2. Step 2: Use filterValues with a null check

    filterValues { it != null } returns a map with only entries whose values are not null.
  3. Final Answer:

    val filtered = map.filterValues { it != null } -> Option B
  4. Quick Check:

    filterValues filters map entries by value condition [OK]
Quick Trick: Use filterValues { it != null } to exclude null values [OK]
Common Mistakes:
MISTAKES
  • Filtering keys instead of values
  • Using mapValues with !! risking exceptions
  • Filtering for null values instead of excluding them

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes