https://kotlinlang.org logo
Title
a

Ayfri

01/27/2022, 1:19 PM
Hi, I have a list of numbers, and I want to sort by descending this list by the number of time it appears in the list and group it by Pair<number of time it appears, value> Example :
[5, 5, 2, 2, 2, 1, 8, 3, 3, 3, 3]
I want to sort it to
[(4, 3), (3, 2), (2, 5), (1, 1), (8, 8)]
, I do not care about sorting by value For now I have this
numbers.groupingBy { it }.eachCount().toList().sortedByDescending { it.second }
And it's working but I'm asking if there is a simple way, I do not care about speed also
m

Michael de Kaste

01/27/2022, 2:04 PM
if you don't care about performance your way is probably the way, although you need to switch first and second of the resulting map if you want it conform your example output;
numbers.groupingBy { it }.eachCount().map { (k, v) -> v to k }.sortedByDescending { it.first }
a

Ayfri

01/27/2022, 7:18 PM
Okay I see, thanks !