What is the easiest way to get a diff of two `List...
# stdlib
o
What is the easiest way to get a diff of two `List<Int>`'s?
minus()
won't do it, since
list2 - list1
only shows what
list2
has what
list1
hasn't.
Or maybe I should just use minus() twice, list2 - list1 and list1 - list2
Think I'm going to do that, thanks guys
k
rubber duck
e
Copy code
fun <T> diffCounts(a: Iterable<T>, b: Iterable<T>): Map<T, Int> = buildMap {
    for (elem in a) put(elem, getOrElse(elem) { 0 } + 1)
    for (elem in b) put(elem, getOrElse(elem) { 0 } - 1)
    values.removeAll(setOf(0))
}
n
Would a `list2.zip(list1).map { it.first - it.second }`not suffice?
e
@nkiesel that performs a completely different operation.
Copy code
listOf(1, 2, 3) - listOf(2, 3, 4) == listOf(1)
diffCounts(listOf(1, 2, 3), listOf(2, 3, 4)) == mapOf(1 to 1, 4 to -1)
listOf(2, 3, 4).zip(listOf(1, 2, 3)) { first, second -> first - second } == listOf(1, 1, 1)
n
I guess it was not clear to me what "diff of two `List<Int>`" was asking for. I my view, both interpretations would make sense.
e
since the follow-up message was that
list2 - list1
and
list1 - list2
together were useful for OP, I think it was clear which interpretation they meant
n
touché