frellan
02/05/2019, 9:58 PMmap
stuff instead but I can’t figure out how to do this. I’m essentially looping over a sequence and I want to place things into three different lists, like partition
but for three output collections instead of two. Is there some general function or a combination that can do this?
val success: MutableList<String> = ArrayList()
val failed: MutableList<String> = ArrayList()
val ignored: MutableList<String> = ArrayList()
for (string in strings) {
val result = doStuff(string)
when {
result != null -> success.add(ingredient)
other condition -> ignored.add(string)
else -> failed.add(string)
}
}
Joe
02/05/2019, 10:04 PMRuckus
02/05/2019, 10:07 PMstrings.groupBy {
val result = duStuff(string)
when {
result != null -> "success"
other condition -> "ignored"
else -> "failed"
}
}
would give a Map<String, List<String>>
with the three keys (success
, ignored
, failed
).karelpeeters
02/05/2019, 10:10 PMkarelpeeters
02/05/2019, 10:10 PMBoolean?
would be safer 🧌Seri
02/05/2019, 10:12 PMfun main() {
val strings = listOf("a", "b", "c")
print(strings.groupBy { doStuff(it) })
}
sealed class StringResult {
object Success: StringResult()
object Ignored: StringResult()
object Failed: StringResult()
}
fun doStuff(string: String): StringResult =
when(string) {
"a" -> StringResult.Success
"b" -> StringResult.Ignored
else -> StringResult.Failed
}
prints out
{StringResult$Success@7e0babb1=[a], StringResult$Ignored@5ba23b66=[b], StringResult$Failed@c818063=[c]}
karelpeeters
02/05/2019, 10:12 PMSeri
02/05/2019, 10:12 PMSeri
02/05/2019, 10:13 PMSeri
02/05/2019, 10:14 PMobject
cases to data class
and give them fields to fill in with doStuff()
Seri
02/05/2019, 10:14 PMfrellan
02/05/2019, 10:17 PMgroupBy
, I have lists now but I can just as easily use a hash. Will read up on sealed classes as well 🙂dmcg
02/05/2019, 11:50 PMdmcg
02/06/2019, 10:03 AMfun <T> Iterable<T>.partitioned(vararg predicates: (T) -> Boolean): List<List<T>> =
predicates.map { groupBy { predicates.asIterable().firstMatch(it) }.getOrDefault(it, emptyList())}
private fun <T> Iterable<(T) -> Boolean>.firstMatch(item: T): ((T) -> Boolean)? = this.find { it(item) }