如何使用java从两个列表中获取不常见元素的列表?

2023-12-22

我需要在比较两个列表时获取不常见元素的列表。 前任:-

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

在这里,我想要另一个列表中的 readAllName 列表(“aaa”、“ccc”、“ddd”)中的不常见元素。 不使用remove()和removeAll()。


假设预期输出是aaa, ccc, eee, fff, xxx(所有不常见的物品),你可以使用List#removeAll http://docs.oracle.com/javase/7/docs/api/java/util/List.html#removeAll%28java.util.Collection%29,但是您需要使用它两次才能获取 name 中但不在 name2 中的项目以及 name2 中但不在 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 or removeAll- 在这种情况下,您可以简单地运行两个循环:

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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用java从两个列表中获取不常见元素的列表? 的相关文章

随机推荐