计算具有重复项的两个列表的差异 [英] Calculating difference of two lists with duplicates
问题描述
我有两个列表。
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 2));
List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 3, 4));
我想删除 list2
来自 list1
,正好与 list2
中包含的次数一样多。在上面的示例中:当我们删除列表1中存在于列表2中的元素时,我们应该得到结果 [1,2]
(仅出现一次 2
应该从 list1
中删除,因为 list2
只包含一个<$的实例c $ c> 2 )。
I want to remove the elements contained in list2
from list1
, precisely as many times as they are contained in list2
. In the example above: when we remove elements in list 1 which exist in list 2, we should get as result [1, 2]
(only one occurrence of 2
should be removed from list1
because list2
contains only one instance of 2
).
我试过 list1.removeAll(list2);
但我得到的结果列表只包含 [1]
。
I tried with list1.removeAll(list2);
but I got as result list containing only [1]
.
实现这一目标的最佳方法是什么?迭代两个列表同时对我来说似乎有点难看。
What is the best way to achieve this? Iterate through both lists simultaneous seems a bit ugly for me.
推荐答案
如果我理解正确,你只想删除一个 2
来自 list1
的元素,而不是所有元素。您可以迭代 list2
并尝试从 list1
中删除每个元素。请记住,如果 list2
不能包含重复项,则有更有效的方法。
If I understand correctly, you only want to remove a single 2
element from list1
rather than all of them. You can iterate over list2
and attempt to remove each element from list1
. Keep in mind that there are more efficient methods than this if list2
cannot contain duplicates.
var list1 = new ArrayList<>(List.of(1, 2, 2));
var list2 = List.of(2, 3, 4);
list2.forEach(list1::remove);
list1
现在包含以下内容:
[1, 2]
请参阅 starman1979的答案了解相同的解决方案,但使用的是lambda而不是方法参考。
See starman1979's answer for the same solution, but using a lambda rather than a method reference.
这篇关于计算具有重复项的两个列表的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!