如何使用Java从两个列表中获取不常见元素的列表? [英] How to get the list of uncommon element from two list using java?

查看:45
本文介绍了如何使用Java从两个列表中获取不常见元素的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在比较两个列表时,我需要获取不常见元素的列表.例如:-

I need to get the list of uncommon element while comparing two lists . ex:-

List<String> readAllName = {"aaa","bbb","ccc","ddd"};
List<String> selectedName = {"bbb","ccc"};

在这里,我要从另一个列表中的readAllName列表("aaa","ccc","ddd")中获取不常见的元素.不使用remove()和removeAll().

here i want uncommon elements from readAllName list ("aaa","ccc","ddd") in another list. Without Using remove()and removeAll().

推荐答案

假定预期输出为 aaa,ccc,eee,fff,xxx (所有非常见项目),则可以使用 List#removeAll ,但是您需要使用它两次才能同时获得名称中的项目(但不包含名称2中的项目)以及名称2中而非名称中的项目:

Assuming the expected output is aaa, ccc, eee, fff, xxx (all the not-common items), you can use List#removeAll, but you need to use it twice to get both the items in name but not in name2 AND the items in name2 and not in name:

List<String> list = new ArrayList<> (name);
list.removeAll(name2); //list contains items only in name

List<String> list2 = new ArrayList<> (name2);
list2.removeAll(name); //list2 contains items only in name2

list2.addAll(list); //list2 now contains all the not-common items


根据您的修改,您不能使用 remove removeAll -在这种情况下,您可以简单地运行两个循环:


As per your edit, you can't use remove or removeAll - in that case you can simply run two loops:

List<String> uncommon = new ArrayList<> ();
for (String s : name) {
    if (!name2.contains(s)) uncommon.add(s);
}
for (String s : name2) {
    if (!name.contains(s)) uncommon.add(s);
}

这篇关于如何使用Java从两个列表中获取不常见元素的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆