https://kotlinlang.org logo
v

v79

03/22/2020, 9:49 AM
I have a collections groupBy / filter / map / reduce challenge I can't quite get right. Can anyone help? I think I might be trying to do to much in a single line of code: given:
Copy code
allTags [
			tag { category: "genre", value: "classical", count=0, multiple=false },
			tag { category: "genre", value: "jazz",, count=0, multiple=false },
			tag { category: "composer", value: "mahler", count=0, multiple=false },
			tag { category: "composer", value: "bach", count=0, multiple=false },
			tag { category: "genre", value: "classical", count=0, multiple=false },
			tag { category: "composer", value: "bach", count=0, multiple=false },
	]
I want:
Copy code
groupedList [
			tag { category: "genre", value: "classical", count=2, multiple=true },
			tag { category: "genre", value: "jazz", count=1, multiple=false },
			tag { category: "composer", value: "mahler", count=1, multiple=false }
			tag { category: "composer", value: "bach", count=2, multiple=true }
	]
// TODO: this isn't counting correctly
val groupedList = allTags.groupBy { it.label }.values.map { it.reduce { acc, item -> Tag(category = item.category, label = item.label, url =  item.url, postCount = item.postCount++, hasPosts = item.postCount > 1) } }
s

spand

03/22/2020, 10:14 AM
There is no label in your objects
But it seems you need to group by category, value then map each list to the wanted value (seems simpler than using reduce)
v

v79

03/22/2020, 12:30 PM
Sorry, label=value. I keep changing the model.
2 Views