Nir
01/23/2021, 10:05 PMfun List<Food>.toAllergenPossibilities() = asSequence()
.flatMap { food -> food.allergens.map { it to food.ingredients } }
.groupingBy { (allergen, _) -> allergen }
.foldTo(mutableMapOf(),
initialValueSelector = { _, (_, ingredients) -> ingredients.toMutableSet() }) { _, set, (_, ingredients) ->
set.apply { retainAll(ingredients) }
}
fun List<Food>.toAllergenPossibilities() = asSequence()
.flatMap { food -> food.allergens.map { it to food.ingredients } }
.groupingBy { (allergen, _) -> allergen }
.mapValues { it.second }
.foldTo(mutableMapOf(),
initialValueSelector = { _, ingredients -> ingredients.toMutableSet() }) { _, set, ingredients ->
set.apply { retainAll(ingredients) }
}
ilya.gorbunov
01/25/2021, 2:43 PMIterator<Pair<T, K>>
requires to allocate a pair for every element, this would significantly increase memory traffic of groupingBy
operations.Nir
01/25/2021, 2:46 PMvalueOf
also a conscious decision for perf reasons or was it simply not considered?