java两个集合的并集怎么求

16次阅读
没有评论

共计 473 个字符,预计需要花费 2 分钟才能阅读完成。

可以使用 addAll() 方法来求两个集合的并集。示例如下:

import java.util.HashSet;
import java.util.Set;

public class Main {public static void main(String[] args) {Set<Integer> set1 = new HashSet<>();
        set1.add(1);
        set1.add(2);
        set1.add(3);

        Set<Integer> set2 = new HashSet<>();
        set2.add(3);
        set2.add(4);
        set2.add(5);

        Set<Integer> union = new HashSet<>(set1);
        union.addAll(set2);

        System.out.println(" 集合 1:" + set1);
        System.out.println(" 集合 2:" + set2);
        System.out.println(" 并集:" + union);
    }
}

运行结果为:

 集合 1:[1, 2, 3]
集合 2:[3, 4, 5]
并集:[1, 2, 3, 4, 5]

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-05-27发表,共计473字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)