https://kotlinlang.org logo
#stdlib
Title
# stdlib
m

Mikael Ståldal

01/31/2023, 10:09 AM
I need to get the sorted frequency of distinct elements in a List. This seems to do what I need:
Copy code
myList.groupingBy { it }.eachCount().toList().sortedBy { it.second }
Is there any shorter and/or more efficient way of doing this? Maybe some shortcut for
groupingBy { it }
?
k

Klitos Kyriacou

01/31/2023, 12:07 PM
Not shorter, but avoids creation of a temporary ArrayList:
Copy code
myList.groupingBy { it }.eachCount().entries.sortedBy { it.value }
(Also, it returns a
List<Map.Entry>
instead of a
List<Pair>
.)
5 Views