文
章
目
录
章
目
录
学会使用HashSet和Stream API在Java中找到两个数组的并集。在集合论中,一组集合的并集(用U表示)是该集合中所有元素的集合。
例如,两个数组A和B的并集是所有在A中、在B中或在A和B中都存在的元素的集合。
1.使用HashSet求数组并集
要获取两个数组的并集,请按照以下步骤进行操作:
- 将第一个数组推入HashSet实例中。
- 使用addAll()方法将第二个数组中的元素添加到集合中。
- 同样,将更多数组的所有元素添加到集合中(如果有的话)。
- Java程序可获取两个整数数组之间的并集并打印输出。
Integer[] arr1 = {0, 2};
Integer[] arr2 = {1, 3};
HashSet<Integer> set = new HashSet<>();
set.addAll(Arrays.asList(arr1));
set.addAll(Arrays.asList(arr2));
Assertions.assertEquals(Set.of(0, 1, 2, 3), set);
//如果有需要转为数组
Integer[] union = set.toArray(new Integer[0]);
Assertions.assertArrayEquals(new Integer[]{0, 1, 2, 3}, union);
2.使用Java 8 Stream求数组并集
我们可以使用流API迭代两个流中的元素,并使用flatMap()
将两个数组中的项规范化到单个流中,然后将其收集到新的数组中。
使用流可以使我们在同一流管道中对并集项执行其他操作,并将结果收集到各种目标类型中。
Integer[] arr1 = {0, 2};
Integer[] arr2 = {1, 3};
Integer[] union = Stream.of(arr1, arr2)
.flatMap(Stream::of)
.toArray(Integer[]::new);
Assertions.assertArrayEquals(new Integer[]{0, 1, 2, 3}, union);
以上就是Java中计算两个数组的并集的两种常用方法。