为了账号安全,请及时绑定邮箱和手机立即绑定

如果列表之间不相等,则查找项目

如果列表之间不相等,则查找项目

largeQ 2021-08-25 18:16:24
我的项目中有 2 个 ArrayList。我想获得不相等的项目。例如:清单 1 - 清单 2AB ------- AB学士 ------- 学士抄送我想得到这个CC。我这样做:ArrayList<String> alllist= new ArrayList<>(ArrayList<String> 1);for (String i : ArrayList<String> 1) {                for (String j :  ArrayList<String> 2) {                    if (i.equals(j)) {                        alllist.remove(i);                        break;                    }                }            }如果我在 ArrayList 中有 3 或 4 个项目,则此方法有效,但是当我添加 200 个项目时,此方法无法正常工作并得到错误列表。任何的想法?我还能做什么?
查看完整描述

3 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

如果您需要列表 1 中的所有内容但不需要列表 2


1) 遍历第一个列表并将每个元素添加到 HashSet。


2) 使用 set.removeAll(list2) 删除列表 2 中的所有内容。


剩余部分是 list1 中的内容,而不是 list2 中的内容。


如果您需要获取任一列表中的所有内容而不是另一个列表中的所有内容,则可以反向重复此操作。这应该将操作反转为 O(n+m),其中 n 是列表 1 的长度,m 是列表 2 的长度。您的伪代码是 O(n*m)。


HashSet firstButNotSecond = new HashSet(list1);

firstButNotSecond.removeAll(list2);

HashSet secondButNotFirst = new HashSet(list2);

secondButNotFirst.removeAll(list1);


查看完整回答
反对 回复 2021-08-25
?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

ArrayList<String> list2 = new ArrayList(); 

list2.add("AB");

list2.add("BA");

ArrayList<String> list1 = new ArrayList();

list1.add("AB");

list1.add("BA");

list1.add("C");

//remove all the element from the list1 which are also in list2 

list1.removeAll(list2);

System.out.println("Result: " + list1); //only C will left behind


查看完整回答
反对 回复 2021-08-25
  • 3 回答
  • 0 关注
  • 174 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信