Count occurrences of each tag using functional programming

Viewed 4148

I've been trying to make a function that returns a Map<String, Int> with the key being a certain tag and the value being the number of occurrences.

The object (simplified) from which I need to extract the info:

class Note {
   List<String> tags
}

The function so far:

private fun extractTags(notes: List<Note>): Map<String, Int> {
    return notes.map { note -> note.tags }
                .groupBy { it }
                .mapValues { it.value.count() }    
}

Right now the compiler gives me a return type mismatch of Map<(Mutable)Set<String!>!, Int> and I'm not certain I'm getting the desired result (as I still can't test this properly).

I'm expecting a result something in the lines of:

(tag1, 1)
(tag2, 4)
(tag3, 14)
...
4 Answers

Excuse me for this late solution, but it is be the best one: as I think when you are using Kotlin you have the standard library that give you a better syntax, shorter and cleaner than the Java 8 streams.

private fun extractTags(notes: List<Note>): Map<String, Int> = notes.flatMap { it.tags }//list of String
        .groupBy { it }//list of Map.Entry<String,List<String>> //List<Map.Entry<String,List<String>>>
        .map {
            Pair(it.key, it.value.size)
        }//list of pairs(tag, count) // List<Pair(String,Int) 
       .toMap()//creat a map from the list of pairs
Related