Java 使用set从arraylist中删除重复项

Java 使用set从arraylist中删除重复项,java,arraylist,set,Java,Arraylist,Set,有两个重复的集合set1={1,2,3,4,5}set2={1,3,6,7},结果应该是set3={2,4,5,6,7} 请允许我重申,我想使用集合界面,结果集应该是自然有序的。您可以尝试以下方法- Set set1, set2; Set newSet = new HashSet(set1); newSet.addAll(set2); 找到十字路口 找到工会 从并集中减去交点 代码: public static void main(String[] args) { Set<

有两个重复的集合
set1={1,2,3,4,5}
set2={1,3,6,7}
,结果应该是
set3={2,4,5,6,7}
请允许我重申,我想使用集合界面,结果集应该是自然有序的。

您可以尝试以下方法-

Set set1, set2;
Set newSet = new HashSet(set1);
newSet.addAll(set2);
  • 找到十字路口
  • 找到工会
  • 从并集中减去交点
代码:

 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);
    }
}
2
4
5
6
7

到目前为止你都试了些什么?你看过
设置界面了吗?看过,这是一个面试问题。我们想帮助人们,但在发布问题之前请先查看谷歌:)我不知道“看这是一个面试问题”如何回答我的问题……结果集会被排序吗?正确吗?你不应该得到并集,得到交集,然后从并集中移除交集吗?