In Java, I can create a map using the toMap collec...
# announcements
q
In Java, I can create a map using the toMap collector, like this:
Copy code
Stream.of(...)
    .toMap(
        keySelector,
        valueTransform,
        (x, y) -> {
            if (x.getTimestamp().isBefore(y.getTimestamp())) return x;
            else return y;
        });
If there would be duplicate values then the third argument determines what to do about it. In Kotlin, the
associateBy
function always keeps the most recent value. Is there a way to create a map the way Java does, where I get to decide what to do with duplicates?
n
Yeah, you can use a groupingBy
associate (and friends) is intended to be the simple function for the common use case, the equivalent of
map
basically
r
for example
Copy code
listOf(1, 2, 3, 4, 5)
    .groupingBy { it % 2 }
    .reduce { key, accumulator, element -> accumulator * element }
gets you
Copy code
{1=15, 0=8}
(in
reduce
,
accumulator
is the value currently associated with
key
and
element
is the one that is trying to be new one) there is also
fold
when you want to also do some type changing mapping, not just selecting or simple operations like I did
q
Thank you. I'd used groupingBy previously, but not much, and didn't think about it here. My example becomes:
Copy code
listOf(...)
    .groupingBy(keySelector)
    .reduce { _, x, y -> if (x.timestamp.isBefore(y.timestamp)) x else y }
2
n
yeah, groupingBy is very nice, I miss it in other languages
if you don't care too much about the efficiency/laziness of it all then it's also possible to do
.associate
followed by
.mapValues
, probably would be a little more readable arguably
since you'd just be able to call
min
minBy
rather
maybe groupBy followed by mapValues, actually. anyhow, doesn't matter.
q
I'll play with those suggestions and see if anything strikes as preferable. Thanks again!