Java

java两个集合的并集怎么求

小亿
94
2024-05-11 14:32:49
栏目: 编程语言

可以使用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]

0
看了该问题的人还看了