2

I'd like to filter out all the pairs with empty values

val mapOfNotEmptyPairs: Map<String, String> = mapOf("key" to Some("value"), "secondKey" to None)

expected:

print(mapOfNotEmptyPairs)
// {key=value}

2 Answers2

2

Vanilla Kotlin

val rawMap = mapOf<String, String?>(
    "key" to "value", "secondKey" to null)
 
// Note that this doesn't adjust the type. If needed, use
// a cast (as Map<String,String>) or mapValues{ it.value!! }
val filteredMap = rawMap.filterValues { it != null }

System.out.println(filteredMap)

p.s When using Arrow Option

val rawMap = mapOf<String, Option<String>>(
    mapOf("key" to Some("value"), "secondKey" to None)

val transformedMap = rawMap
   .filterValues { it.isDefined() }
   .mapValues { it.value.orNull()!! } 

p.p.s When using Arrow Option and their filterMap extension function;

val rawMap = mapOf<String, Option<String>>(
    mapOf("key" to Some("value"), "secondKey" to None)

val transformedMap = rawMap
   .filterMap { it.value.orNull() } 

Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51
  • Thank you for the input. Unfortunately, you have answered the wrong question. Please consider in the question there is no null object, instead, you can find Option of String. Filtering null values from the map is a completely different question. Additionally, it is a trivial observation that one can easily transform a case when Option is None to null, and then filter the map. – Marcin Charęziński Apr 02 '21 at 21:54
  • The type of your map is and not >, so I was assuming Some / None was a copy/paste issue from Scala or similar – Stefan Haustein Apr 02 '21 at 22:26
  • Map is the type I'd like to have as a result. Obviously, it doesn't compile the way I wrote it. So we can narrow down the question to find a function to transform from > to . Ideally not using nulls. – Marcin Charęziński Apr 02 '21 at 22:32
  • For kotlin maps, arrow provides fiterMap, which filters out null values, see edit – Stefan Haustein Apr 02 '21 at 22:53
1
val mapOfNotEmptyPairs =
        mapOf("key" to Some("value"), "secondKey" to None)
            .filterValues { it is Some<String> } // or { it !is None } or { it.isDefined() }
            .mapValues { (_, v) -> (v as Some<String>).t }