dave08
12/22/2022, 11:44 AMdata class Foo(val bar: String, val baz: Int)
and I want to only have a list with a unique bar
with the max baz
. Say [0] -> bar = "one", baz = 1 and [1] -> bar = "one", baz = 2, the resulting list should be in the same order and only contain [2]... how do I do this in the most concise and efficient way?Ties
12/22/2022, 11:55 AMdave08
12/22/2022, 11:58 AMyou can then do a .map{it.baz}.max() on those valuesI need a list of Foo, not a list of bars... And groupBy creates an intermediary map that I would have rathered to avoid...
Ties
12/22/2022, 11:58 AMTies
12/22/2022, 12:00 PMdave08
12/22/2022, 12:04 PMdave08
12/22/2022, 12:08 PMgroupBy { it.baz }.mapValues { it.value.maxBy { foo -> foo.bar } }
, could probably do the trick...dave08
12/22/2022, 12:11 PM.values
from the map...Ties
12/22/2022, 12:11 PMTies
12/22/2022, 12:11 PMdave08
12/22/2022, 12:12 PMTies
12/22/2022, 12:14 PMTies
12/22/2022, 12:15 PMdave08
12/22/2022, 12:16 PMTies
12/22/2022, 12:17 PMKlitos Kyriacou
12/22/2022, 5:31 PMmapValues
followed by values
you can use map
which avoids creating a second intermediate Map:
groupBy { it.bar }.map { it.value.maxBy(Foo::baz) }
Also, on the JVM only, the following avoids creating an intermediate map of Lists, of Foos but instead creates a Map of Foos directly:
fold(LinkedHashMap<String, Foo>()) { map, foo ->
map.merge(foo.bar, foo, maxBy(comparingInt(Foo::baz)))
map
}.values
(For whatever reason, Java's useful Map.merge
function is not available in Kotlin's MutableMap
itself, but only when it's a typealias of Java's Map.)phldavies
12/22/2022, 11:45 PMgroupingBy { it.bar }.reduce { _, a, b -> if(a.baz > b.baz) a else b }.values