How to find the union of two arrays in Java?

To find the union of two arrays in Java, you can follow these steps:

  1. First, create a new ArrayList to store the elements of the union.
  2. Traverse the first array, add all of its elements to an ArrayList, ensuring there are no duplicates.
  3. Iterate through the second array again and add elements that are not already in the ArrayList.
  4. Finally, convert the ArrayList to an array and return it.

Below is an example code:

import java.util.ArrayList;
import java.util.Arrays;

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

        String[] union = getUnion(array1, array2);

        System.out.println(Arrays.toString(union));
    }

    public static String[] getUnion(String[] array1, String[] array2) {
        ArrayList<String> unionList = new ArrayList<>();

        // 将第一个数组的所有元素添加到ArrayList中
        for (String element : array1) {
            if (!unionList.contains(element)) {
                unionList.add(element);
            }
        }

        // 将第二个数组中不在ArrayList中的元素添加到ArrayList中
        for (String element : array2) {
            if (!unionList.contains(element)) {
                unionList.add(element);
            }
        }

        // 将ArrayList转换为数组
        String[] unionArray = new String[unionList.size()];
        unionArray = unionList.toArray(unionArray);

        return unionArray;
    }
}

In the example above, array1 and array2 are the two arrays to be unioned. By calling the getUnion() method, a new array containing the union of the two arrays will be returned. Finally, the result array is printed out using the Arrays.toString() method.

By running the example code above, you will get the output [A, B, C, D, E, F], which is the union of two arrays.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds