【问题标题】:RxKotlin COUNT with GROUP BY and return a listRxKotlin COUNT 与 GROUP BY 并返回一个列表
【发布时间】:2021-07-06 11:00:34
【问题描述】:

我有一个 Kotlin 中重复出现的元素的列表,比如说:

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

我想按它们的值以及它们出现的次数对它们进行分组,因此输出将是成对的:

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

我已经解决了在 Kotlin 中使用的问题如下:

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

我想在 RxKotlin 中编写相同的代码进行学习,并尝试了以下但不知道如何应用 map/flatMap 来达到结果。

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

【问题讨论】:

  • 我建议看看如何format your code。我现在已经为您编辑了它,但只是为了将来记住一些事情!
  • 感谢@HenryTwist

标签: kotlin rx-java rx-kotlin rx-kotlin2


【解决方案1】:

试试这样的:

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

【讨论】:

  • 谢谢。在你回答之前我已经解决了,但是这是正确的答案。
猜你喜欢
  • 2020-12-20
  • 2011-04-05
  • 2014-04-26
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2021-08-06
相关资源
最近更新 更多