Search code examples
kotlinrx-javarx-kotlinrx-kotlin2

RxKotlin COUNT with GROUP BY and return a list


I have a list of recurring elements in Kotlin, say:

val result = arrayListOf<String>("AA", "BB", "CC", "AA", "BB")

I would like to group them by their value along with how many times they appear, so the output would be pairs of:

{"AA", 2}, {"BB", 2}, {"CC", 1}

I have resolved the problem using in Kotlin as follows:

val ans = result.map { it.value }
            .groupBy { it }
            .map { Pair(it.key, it.value.size) }
            .sortedByDescending { it.second }

I want to write same code in RxKotlin for learning and tried with the following but do not know how to apply map/flatMap to achieve the result.

val source = Observable.fromIterable(result)
source.groupBy{ it }.subscribe { showresult(it) }

Solution

  • Try something like this:

    source.groupBy { it }
    .flatMapSingle { g -> g.count().map { Pair(g.getKey(), it) } }
    .toSortedList { a, b -> b.second.compareTo(a.second) }
    .subscribe { list -> println(list) }