Java Example – Array Union
The following example demonstrates how to use the union() method to compute the union of two arrays:
Main.java File
import
java
.
util
.
Arrays
;
import
java
.
util
.
HashSet
;
import
java
.
util
.
Set
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
throws
Exception
{
String
[
]
arr1
=
{
"
1
"
,
"
2
"
,
"
3
"
}
;
String
[
]
arr2
=
{
"
4
"
,
"
5
"
,
"
6
"
}
;
String
[
]
result_union
=
union
(
arr1
,
arr2
)
;
System
.
out
.
println
(
"
The result of the union is as follows:
"
)
;
for
(
String
str
:
result_union
)
{
System
.
out
.
println
(
str
)
;
}
}
//
Compute the union of two string arrays, leveraging the uniqueness of set elements
public
static
String
[
]
union
(
String
[
]
arr1
,
String
[
]
arr2
)
{
Set
<
String
set
=
new
HashSet
<
String
(
);
for
(
String
str
:
arr1
)
{
set
.
add
(
str
)
;
}
for
(
String
str
:
arr2
)
{
set
.
add
(
str
)
;
}
String
[
]
result
=
{
}
;
return
set
.
toArray
(
result
)
;
}
}
The output of the above code is:
The result of the union is as follows:
3
2
1
6
5
4
Java Examples