1

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) }
Henry Twist
  • 5,666
  • 3
  • 19
  • 44
user1154390
  • 2,331
  • 3
  • 25
  • 32
  • I would recommend taking a look at how to [format your code](https://stackoverflow.com/help/formatting). I have edited it for you now, but just something to keep in mind for the future! – Henry Twist Apr 10 '21 at 23:29

1 Answers1

0

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) }
akarnokd
  • 69,132
  • 14
  • 157
  • 192