xxfast
09/20/2021, 1:11 AMval actual = listOf(
Item(type = A, value = 1),
Item(type = B, value = 2),
Item(type = B, value = 3)
)
val expect = mapOf(
A to listOf(Item(type = A, value = 1)),
B to listOf(Item(type = B, value = 2), Item(type = B, value = 3)),
C to emptyList()
)
actual
.groupByTo(
mutableMapOf(
A to mutableListOf(),
B to mutableListOf(),
C to mutableListOf(),
)
) { item -> item.type }
but this is not quite readable, and was wondering if there’s a better waylistOf(A, B, C)
.map { type -> type to actual
.filter { item -> item.type == type }
}
just had to reverse my way of thinkingdave08
09/20/2021, 2:35 AMlist(A,B,C).map { it to mutableListOf() }
to make the map?Tobias Suchalla
09/20/2021, 6:00 AMval map: Map<Type, List<Item>> = actual.groupBy { it.type }
However, Type C
would be missing in the map as there is no such type in actual
.val itemsForC = map[C] ?: emptyList()
Roukanken
09/20/2021, 7:49 AMval result = actual
.groupBy { it.type }
.withDefault { emptyList() }
This assumes that C is subtype of common type of A & B, and not some higher supertype ofc, otherwise you would have to do some extra casting in there somewhere
but this gets you map that has values from list as you want, and at everything else that is a valid key, it will respond with empty listephemient
09/20/2021, 8:08 AMval result = actual
.groupBy<Item, SupertypeOfABC> { it.type }
.withDefault { emptyList() }