如何使用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);
}