Java 如何合并两个不重复的ArrayList?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16520046/
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-08-16 07:15:59  来源:igfitidea点击:

How to merge two ArrayLists without duplicates?

javaarraylist

提问by Sen

I have two arrayLists

我有两个数组列表

ArrayList one = {A, B, C, D, E}
ArrayList two = {B, D, F, G}  

I want to have my final ArrayList which will have Allthe elements of one and the elements which are only in two and not in one.

我想要我的最终 ArrayList,它将包含一个的所有元素和只有两个而不是一个的元素。

So ArrayList final = {A, B, C, D, E, F, G}.

所以 ArrayList final = {A, B, C, D, E, F, G}。

How can I do this?

我怎样才能做到这一点?

采纳答案by John B

for (Object x : two){
   if (!one.contains(x))
      one.add(x);
}

assuming you don't want to use the set suggested in the comment. If you are looking for something fancier than this please clarify your question.

假设您不想使用评论中建议的集合。如果您正在寻找比这更有趣的东西,请澄清您的问题。

回答by Ankit

you can do something like this:

你可以这样做:

ArrayList<Object> result = new ArrayList<>();
result.addAll(one);

for(Object e: two){
    if(!result.contains(e))
        result.add(e);
}

回答by Sanjaya Liyanage

Try this kind of thing. As Setdoesn't allow duplicates you can add only the changes

试试这种东西。由于Set不允许重复,您只能添加更改

ArrayList<String> a=new ArrayList<>();
a.add("a");
a.add("b");
ArrayList<String> b=new ArrayList<>();
a.add("a");
a.add("c");
Set<String> s=new HashSet<String>();
s.addAll(a);
s.addAll(b);
a=new ArrayList<>(s);
for(String r:a){
    System.out.println(r);
}

回答by Puce

Either:

任何一个:

Set<Foo> fooSet = new LinkedHashSet<>(one);
fooSet.addAll(two);
List<Foo> finalFoo = new ArrayList<>(fooSet);

or

或者

List<Foo> twoCopy = new ArrayList<>(two);
twoCopy.removeAll(one);
one.addAll(twoCopy);