molikuner
03/11/2020, 9:19 PMval x = listOf("a", "a", "b").function(listOf("a", "c"))
where
x == listOf("a", "b")
When using
listOf("a", "a", "b") - listOf("a", "c")
I get
x == list("b")
but I want to have one a
in there.
I know that I could do:
var a = listOf("a", "a", "b")
val b = listOf("a", "c")
b.forEach {
a = a - it
}
But I don’t really like the forEach
and var
in that solution.Eivind Nilsbakken
03/11/2020, 11:32 PMfold
and minus
with a single element (a.minus(b)
would remove all occurences of "a"):
val a = listOf("a", "a", "b")
val b = listOf("a", "c")
val x = b.fold(a) { result, element ->
result.minus(element)
}
println(x) // [a, b]
Eivind Nilsbakken
03/11/2020, 11:33 PM-
instead of .minus()
. I didn't know that worked on lists. 😮Kroppeb
03/12/2020, 12:01 AMmolikuner
03/12/2020, 8:56 AMEivind Nilsbakken
03/12/2020, 9:12 AMa
.
val a = listOf("a", "a", "b")
val b = listOf("a", "c")
val c = b.groupingBy { it }.eachCount() as MutableMap<String, Int>
val x = a.filter {value ->
c[value] = (c[value] ?: 0) - 1
c[value]!! < 0
}
println(x) // [a, b]
a
. Eg. with a.size == 10000
and b.size == 5000
they take 376 vs 7 millis to execute. The first approach is faster than the second though, which isn't surprising, since it saves time on not creating and using the lookup map. (https://pl.kotl.in/B0TnYmQ3Y)