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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14645319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:56:55  来源:igfitidea点击:

How to get the list of uncommon element from two list using java?

java

提问by Arunprasad

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"};

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

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

回答by assylias

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:

假设预期的输出是aaa, ccc, eee, fff, xxx(所有不常见的项目),您可以使用List#removeAll,但您需要使用它两次才能同时获取 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


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

根据您的编辑,您不能使用removeor 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);
}

回答by RNJ

You can use the Guava libraries to do this. The Setsclass has a differencemethod

您可以使用 Guava 库来执行此操作。该集合类有一个区别方法

You would have to run it twice I think to get all the differences from both sides.

我认为你必须运行它两次才能获得双方的所有差异。