有没有办法在rx-java/kotlin中对groupBy键进行排序?
问题描述:
下面是一个例子:有没有办法在rx-java/kotlin中对groupBy键进行排序?
Observable.fromIterable(listOf("4444", "22", "333", "1", "55555"))
.groupBy { it.hashCode() }
.subscribe { group ->
group.toList().subscribe { list -> println("${group.key} $list") }
}
输出:
1600 [22]
49 [1]
50643 [333]
50578165 [55555]
1600768 [4444]
如何以升序排序的键/降序或使用自定义排序比较?
答
其中一个解决方案是使用sorted
功能自定义Comparator
:
Observable.fromIterable(listOf("4444", "22", "333", "1", "55555"))
.groupBy { it.hashCode() }
.sorted { o1, o2 ->
o1.key?.minus(o2.key ?: 0) ?: 0
}
.subscribe { group ->
group.toList().subscribe { list -> println("${group.key} $list") }
}
输出:
49 [1]
1600 [22]
50643 [333]
1600768 [4444]
50578165 [55555]