`listOf(1, 2, 3).containsAll(listOf(2, 2))` return...
# stdlib
m
listOf(1, 2, 3).containsAll(listOf(2, 2))
returns true. What's the best alternative that will tell me correctly that the first list doesn't, in fact, contain all the elements of the second list? I want to consider the amount of items.
My current alternative is
listOf(2, 2).toMutableList().also { list -> listOf(1, 2, 3).forEach { list.remove(it) }.isEmpty()
, but it seems a bit much.
j
What do you use this list for? Wouldn't it be more appropriate to use a frequency map for this? (It wouldn't necessarily make this operation easier, but I'm curious)
m
I need to generate a diff of the two lists, and I am also interested in the order, which is why it's a list and not a map currently.
But yes, I could transform these lists into frequency maps. I don't think it would be shorter/easier though.
j
I guess if you want to create a full diff of the lists you might need a bigger algorithm loop anyway. How would you use what you're asking for in your algorithm? You might want to check out libraries for this to be honest. Something like DiffUtils: https://github.com/java-diff-utils/java-diff-utils
m
Now that you made me look at my original question again, I'm not sure why I asked about
containsAll
, my problem was with the
minus
operator. Which has the same problem, but shows my actual intent. My original code was:
val missingItems = expectedItems - currentItems
val extraItems = currentItems - expectedItems
This had the problem, that the
minus
operator does not consider counts, so this didn't behave as expected when expected/current items had duplicates, which is a valid state for them to be in.
👌 1
I replaced that with what I posted, which now works correctly, but seems like a lot for what it does.
A library seems overkill for something that is 10 lines of code total anyway.
j
I misinterpreted what you meant by "diff with order", so yeah maybe the lib is overkill
m
And all I cared about order is that if
missingItems
and
extraItems
are both empty, but the two lists are not equal, then they must be in different order (but I don't actually care where).
k
I think Kotest collection matchers do what you want. You could have a look at how they're implemented.