在java中合并两个List而不重复

时间:2015-05-26 05:54:31

标签: java

**请帮我解决这个问题

    List<String> list1 = {"a","b","c","d","aa","e","f","g"};        
    List<String> list2 = {"a","j","k","l","aa","x","y","z"};

在最终结果中,我想要像

这样的东西
    result = {"a","b","c","d","j","k","l","aa","e","f","g","x","y","z"};

3 个答案:

答案 0 :(得分:1)

我建议您使用TreeSet,因为它不允许重复元素。 通过将第二个TreeSet添加到第一个TreeSet来迭代第二个TreeSet

OR

您可以使用列表并使用方法contains()并相应地添加。

答案 1 :(得分:0)

您需要将其保存在一个集合中,因为它会保留唯一条目。如果你需要基于keey排序,你将需要TreeSet ...

Set<String> mySet  = new HashSet<String>();
mySet.addAll(list1);
mySet.addAll(list2);

mySet拥有您需要的所有集合。

答案 2 :(得分:0)

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