学习使用 HashSet 类。在集合论中,并集(用 U 表示)集合的集合是集合中所有元素的集合。
例如,两个集合 A 和 B 的并集是所有元素的集合,这些元素要么在 A 中,要么在 B 中,要么同时在 A 和 B 中。
联盟
要获得两个数组的并集,请按照下列步骤操作:
获取两个整数数组之间的并集并打印输出的 Java 程序。
import java.util.Arrays; import java.util.HashSet; public class Main { public static void main(String[] args) { Integer[] firstArray = {0,2,4,6,8}; Integer[] secondArray = {1,3,5,7,9}; HashSet<Integer> set = new HashSet<>(); set.addAll(Arrays.asList(firstArray)); set.addAll(Arrays.asList(secondArray)); System.out.println(set); //convert to array Integer[] union = {}; union = set.toArray(union); System.out.println(Arrays.toString(union)); } }
程序输出。
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
获取两个字符串数组之间的并集并打印输出的 Java 程序。
import java.util.Arrays; import java.util.HashSet; public class Main { public static void main(String[] args) { String[] firstArray = {"A", "B", "C", "D"}; String[] secondArray = {"D", "A", "E", "F"}; HashSet<String> set = new HashSet<>(); set.addAll(Arrays.asList(firstArray)); set.addAll(Arrays.asList(secondArray)); System.out.println(set); //convert to array String[] union = {}; union = set.toArray(union); System.out.println(Arrays.toString(union)); } }
程序输出。
[A, B, C, D, E, F] [A, B, C, D, E, F]
快乐学习!!
地址:https://www.cundage.com/article/union-between-two-arrays.html