Raymond Chenon
Raymond Chenon

Reputation: 12662

Kotlin FP : Convert List<String> to Map<String,Int>

I have a List of String, I want to transform into a Map of occurrences. ( ~ The Map values are the count of many times the String was repeated in the List)

The imperative way, I'd write like the following

fun transformMap(list: List<String>): Map<String, Int> {
    val map = mutableMapOf<String,Int>()
    for(n in list){
        map.put(n,map.getOrDefault(n,0) + 1)
    }
    return map.toMap()
}

How to write this in Functional Programming way ?

In Java 8+, this will be written like this

String[] note;
Map<String, Integer> noteMap = Arrays.stream(note)
         .collect(groupingBy(Function.identity(),
          collectingAndThen(counting(), Long::intValue)));

Upvotes: 5

Views: 2160

Answers (2)

Todd
Todd

Reputation: 31660

You can use Kotlin's Grouping to do this in one line via the Iterable<T>.groupingBy extension:

val myList = listOf("a", "b", "c", "a", "b", "a")
val myMap = myList.groupingBy { it }.eachCount()

println(myMap)
// Prints {a=3, b=2, c=1}

Upvotes: 14

JB Nizet
JB Nizet

Reputation: 691635

You can use streams in Kotlin too. But if you want to avoid streams, you can use fold():

val list = listOf("a", "b", "c", "a")
val histogram = list.fold(mutableMapOf<String, Int>()) { map, s ->
    map[s] = map.getOrDefault(s, 0) + 1
    map
}.toMap()

println(histogram)

Upvotes: 4

Related Questions