可以使用addAll()方法来求两个集合的并集。示例如下:
import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { Setset1 = new HashSet<>(); set1.add(1); set1.add(2); set1.add(3); Set set2 = new HashSet<>(); set2.add(3); set2.add(4); set2.add(5); Set 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]