Writing a Java program to find first non-repeated character in a String is a common programming interview question to test the usage of Set interface provided in Java collection framework.
The solution of this program can be built with a plain for-each loop by traversing each element of the array and manually identifying the duplicates before performing any insert operation but we will be using in-built data structure in Java known as HashSet to provide solution to this question.
HashSet implements the Set interface and does not allow duplicate elements. These particular feature can be used to find the union of multiple arrays whereas retainAll()
method provided in Set interface can be used to find the intersection of multiple arrays.
retainAll()
removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.
Below is the complete Java program implementation:
package com.devglan; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; public class ArrayUnionAndIntersection { public static Set findUnion(Integer[] ... arrays){ Setset = new HashSet<>(); Stream.of(arrays).forEach(array -> set.addAll(Arrays.asList(array))); return set; } public static Set findIntersection(Integer[] ... arrays){ Set intersectionSet = new HashSet<>(Arrays.asList(arrays[0])); Stream.of(arrays).skip(1).forEach(array -> { HashSet set = new HashSet<>(Arrays.asList(array)); intersectionSet.retainAll(set); }); return intersectionSet; } public static void main(String[] args){ Integer[] firstArray = {9, 7, 6, 7, 1, 8}; Integer[] secondArray = {5, 2, 6, 3, 4}; Integer[] thirdArray = {4, 7, 5, 6}; Set union = findUnion(firstArray, secondArray, thirdArray); System.out.println("Output Array after union ***********************"); System.out.println(union); Set intersection = findIntersection(firstArray, secondArray, thirdArray); System.out.println("Output Array after intersection ***********************"); System.out.println(intersection); } } Output: