使用set从arraylist中删除重复项

时间:2015-06-09 09:09:38

标签: java arraylist set

有2套重复set1 ={1,2,3,4,5} set2 = {1,3,6,7},结果应为set3 ={2,4,5,6,7}   请允许我重申我想使用Set接口,结果集应该是自然排序的。

2 个答案:

答案 0 :(得分:2)

  • 找到交叉点
  • 找工会
  • 从联合中减去交集

<强>代码:

new Integer

<强>输出:

 public static void main(String[] args) {

    Set<Integer> set1 = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4, 5));
    Set<Integer> set2 = new HashSet<Integer>(Arrays.asList(1, 3, 6, 7));

    Set<Integer> intersection = new HashSet<Integer>(set1);
    intersection.retainAll(set2);

    // set1 is now the union of set1 and set2
    set1.addAll(set2);

    // set1 is now (union - intersection)
    // All elements in set1 or set2, but not in both set1 & set2
    set1.removeAll(intersection);

    for(Integer n : set1) {
        System.out.println(n);
    }
}

答案 1 :(得分:1)

你可以试试这个 -

Form2