问题描述
我有两个列表.
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 2));
List<Integer> list2 = new ArrayList<>(Arrays.asList(2, 3, 4));
我想从 list1
中删除包含在 list2
中的元素,次数与它们包含在 list2
中的次数相同.在上面的例子中:当我们删除列表 1 中存在于列表 2 中的元素时,我们应该得到结果 [1, 2]
(只有一次出现 2
应该是从 list1
中删除,因为 list2
只包含 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.
推荐答案
如果我理解正确,您只想从 list1
中删除单个 2
元素而不是全部其中.您可以遍历 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.
这篇关于计算两个重复列表的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!