Hmm this makes me wonder: does `groupingBy` have a...
# advent-of-code
k
Hmm this makes me wonder: does
groupingBy
have any use cases other than
eachCount
?
r
Not sure, to be honest. So far everything done with groupingBy seems to be done just as easily with groupBy and the resulting map from that, but maybe it's a performance thing?
k
Ah and
groupingBy
is lazy vs
groupBy
which is eager.
Funny that there's no
Map<K,T>.eachCount(): Int
r
...what would that do? Return the amount of entries in the map?
k
A
Grouping<T,K>
is basically a lazy
Map<K,List<T>>
, right?
So it would return a
Map<K,Int>
that counts the amounts of `T`s that maps to each
K
.
Now I understand what this comment meant!
❤️ 1
t
Might be a good thing for somebody to propose for the stdlib.
k
I feel like we're going to have a hard time justifying this, it's the first time I've even thought about it myself.
i
Funny that there's no
Map<K,T>.eachCount(): Int
So it would return a
Map<K,Int>
that counts the amounts of `T`s that maps to each
K
.
Wouldn't it be
1
for each key in the map?
r
Nope, it would count the amounts of keys per value, not values per key, if I understood correctly
👍 1
k
Yeah I'm sorry for wording that strangely and messing up the generics simple smile
i
In that case it would return
Map<T, Int>
. I don't find that consistent enough with the existing
eachCount
to name it with the same name.
k
list.groupBy { f(it) }.eachCount()
should return the same thing as
list.groupingBy { f(it) }.eachCount()
.
k
is there any performance diff in using
string.groupBy { it }.mapValues{it.values.size}
and
string.groupingBy { it }.eachCount()
?
k
Yes, the first one build a throwaway map while the second lazily counts everything.
k
@karelpeeters I don't understand the
lazy
concept clearly😅
k
Do you know how Java streams or Kotlin sequences work? A quick example:
(0..100_000_100).asSequence().filter { it % 2 == 0 }.sum()
finishes in
260ms
pretty much instantly
(0..100_000_100).filter { it % 2 == 0 }.sum()
builds an intermediate list of
100_000_000
elements and that takes 20 seconds.
k
ok I'll do some research 👍🏻