java两个数组取并集
时间: 2023-09-17 21:11:57 浏览: 71
可以使用Java的Set集合来实现两个数组的并集操作。具体实现步骤如下:
1. 将数组转换成Set集合。
2. 使用addAll()方法将第二个数组加入到第一个Set集合中。
3. 将合并后的Set集合转换成数组。
以下是示例代码:
```java
public static int[] union(int[] arr1, int[] arr2) {
Set<Integer> set = new HashSet<Integer>();
for (int num : arr1) {
set.add(num);
}
for (int num : arr2) {
set.add(num);
}
int[] result = new int[set.size()];
int index = 0;
for (int num : set) {
result[index++] = num;
}
return result;
}
```
调用该方法即可实现两个数组的并集操作。
相关问题
java求两个数组的并集
您好,以下是求两个数组的并集的 Java 代码:
```java
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {4, 5, 6, 7, 8};
int[] union = getUnion(arr1, arr2);
for (int i : union) {
System.out.print(i + " ");
}
}
public static int[] getUnion(int[] arr1, int[] arr2) {
HashSet<Integer> set = new HashSet<>();
for (int i : arr1) {
set.add(i);
}
for (int i : arr2) {
set.add(i);
}
int[] union = new int[set.size()];
int index = 0;
for (int i : set) {
union[index++] = i;
}
return union;
}
}
```
希望能对您有所帮助!
Java取两个int数组的交集和并集
Java取两个int数组的交集和并集的代码如下:
```java
public class ArrayIntersectionUnion {
public static void main(String[] args) {
int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 4, 5, 6, 7, 8 };
// 求交集
Set<Integer> intersection = new HashSet<Integer>();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
intersection.add(arr1[i]);
break;
}
}
}
System.out.println("Intersection: " + intersection);
// 求并集
Set<Integer> union = new HashSet<Integer>();
for (int i = 0; i < arr1.length; i++) {
union.add(arr1[i]);
}
for (int j = 0; j < arr2.length; j++) {
union.add(arr2[j]);
}
System.out.println("Union: " + union);
}
}
```
运行结果如下:
```
Intersection: [4, 5]
Union: [1, 2, 3, 4, 5, 6, 7, 8]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)