本文将分享一下如何在​​Java​​中获得两个数组的并集,包含两个数组中的所有不同元素。

通常我们可以使用带有​​HashSet​​​执行并集的去重工作,使用​​addAll()​​​方法将每个数组的所有值添加到​​HashSet​​中。

这是一个最常见的简单的解决方案,该解决方案还将适用于基础数据类型和对象数据。

基础数据类型

下面是两个基础数据类型数组的合并。

package com.fun.ztest.java;

import com.fun.frame.SourceCode;
import org.apache.commons.lang3.ArrayUtils;

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

public class Tdd extends SourceCode {

public static void main(String[] args) {
int[] array1 = {1, 2, 3};

int[] array2 = {2, 4, 6};

Set<Integer> union = new HashSet<>();
union.addAll(Arrays.asList(ArrayUtils.toObject(array1)));
union.addAll(Arrays.asList(ArrayUtils.toObject(array2)));

output(union);

}


}

控制台输出:

package com.fun.ztest.java;

import com.fun.frame.SourceCode;
import org.apache.commons.lang3.ArrayUtils;

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

public class Tdd extends SourceCode {

public static void main(String[] args) {
int[] array1 = {1, 2, 3};

int[] array2 = {2, 4, 6};

Set<Integer> union = new HashSet<>();
union.addAll(Arrays.asList(ArrayUtils.toObject(array1)));
union.addAll(Arrays.asList(ArrayUtils.toObject(array2)));

output(union);

}


}

对象数据类型

下面是实现两个​​String​​数组的并集。

package com.fun.ztest.java;

import com.fun.frame.SourceCode;

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

public class Tdd extends SourceCode {

public static void main(String[] args) {
String[] array1 = {"A", "B", "C", "D"};

String[] array2 = {"C", "D", "E", "F"};

Set<String> union = new HashSet<>();
union.addAll(Arrays.asList(array1));
union.addAll(Arrays.asList(array2));

output(union);

}


}```

控制台输出:


```shell
INFO-> 当前用户:fv,IP:10.60.192.21,工作目录:/Users/fv/Documents/workspace/fun/,系统编码格式:UTF-8,系统Mac OS X版本:10.15.7
INFO-> [A, B, C, D, E, F]

Process finished with exit code 0

Groovy大招

下面开始​​Groovy​​的表演。

public static void main(String[] args) {
def a = [3, 4, 6]
def b = [4, 5, 6]
def integers = a + b as Set
output(integers)

}

控制台输出:

INFO-> 当前用户:fv,IP:10.60.192.21,工作目录:/Users/fv/Documents/workspace/fun/,系统编码格式:UTF-8,系统Mac OS X版本:10.15.7
INFO-> [3, 4, 6, 5]

Process finished with exit code 0

公众号FunTester首发,原创分享爱好者,腾讯云、开源中国和掘金社区首页推荐,知乎八级强者,欢迎关注、交流,禁止第三方擅自转载。