If i have a list of pairs (to and from) and want t...
# stdlib
a
If i have a list of pairs (to and from) and want to get the distinct sorted pairs that occur the most what would be the most functional way of doing it? So
[(1,2) , (3,4), (1,2)]
should return
[(1,2),(3,4)]
i
Doesn't
pairs.distinct()
and then sorting by your criteria help?
a
Yeah lol - I realised after i posted
Oh no wait
I want it sorted by how many times it appears
Not by the actual data inside the pair
Nvm
m
Copy code
listOf(1 to 2, 2 to 3, 1 to 2)
        .groupBy { it }
        .toList()
        .sortedBy { it.second.size }
        .flatMap { it.second } // Or if you want distinct then .map { it.first }
o
listOf(1 to 2, 2 to 3, 1 to 2).groupingBy { it }.eachCount()
should be better performance-wise
a
@orangy worth adding as sequence?
Or should be fine?
o
That depends on the input size. Measure 🙂
a
The list is expected to be 4000 pair elements
Also what is the difference between groupBy and groupingBy
i
worth adding as sequence?
if these are all operations on the list, then it isn't.
Also what is the difference between groupBy and groupingBy
groupBy
immediately produces a map of keys to lists of grouped values, and
groupingBy
allows to apply an aggregating operation to an each list on-the-fly, so the resulting map maps keys to the aggregation result of an each group.
a
all operations on a list
? When are they not? Do you mean things like map/sets?
i
I mean if you're applying groupingBy directly on list, there's no gain in turning it to a sequence beforehand.
a
Oh oh i see
Ok thanks!!