2017-09-16 52 views
1

下面是一個例子:有沒有辦法在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] 

如何以升序排序的鍵/降序或使用自定義排序比較?

回答

1

其中一個解決方案是使用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] 
相關問題