How to Compute the Union of Two Arrays in Java Using HashSet
This tutorial demonstrates step‑by‑step how to obtain the union of two arrays in Java—both primitive and object types—by leveraging a HashSet with addAll, includes full code examples, console output, and a concise Groovy alternative.
The article explains how to compute the union of two arrays in Java, ensuring that all distinct elements from both arrays are retained. The common approach uses a HashSet and its addAll() method to perform deduplication.
Primitive Data Types
For primitive int arrays, the example converts the arrays to object form with ArrayUtils.toObject, adds them to a HashSet<Integer>, and prints the result.
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);
}
}Console output shows the merged set:
INFO-> [1, 2, 3, 4, 6]
Process finished with exit code 0Object Data Types
The same technique works for String arrays, directly adding the arrays to a HashSet<String> without conversion.
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);
}
}The resulting set printed to the console is:
INFO-> [A, B, C, D, E, F]
Process finished with exit code 0Groovy Shortcut
Using Groovy, the union can be expressed more concisely by concatenating two lists and casting the result to a Set:
public static void main(String[] args) {
def a = [3, 4, 6]
def b = [4, 5, 6]
def integers = a + b as Set
output(integers)
}The Groovy version prints:
INFO-> [3, 4, 6, 5]
Process finished with exit code 0These examples illustrate a straightforward, language‑agnostic method for merging arrays and removing duplicates, suitable for both primitive and object data types.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
