2017-09-16 7 views
1

Voici un exemple:Existe-t-il un moyen de trier les clés groupBy dans rx-java/kotlin?

Observable.fromIterable(listOf("4444", "22", "333", "1", "55555")) 
    .groupBy { it.hashCode() } 
    .subscribe { group -> 
     group.toList().subscribe { list -> println("${group.key} $list") } 
    } 

sortie:

1600 [22] 
49 [1] 
50643 [333] 
50578165 [55555] 
1600768 [4444] 

Comment trier les clés dans ordre ascendant/descendant ou en utilisant un comparateur de tri personnalisé?

Répondre

1

Une des solutions est d'utiliser la fonction sorted avec la coutume 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") } 
     } 

Sortie:

49 [1] 
1600 [22] 
50643 [333] 
1600768 [4444] 
50578165 [55555]