HashTable

Union of Array Lists

Pinterest LinkedIn Tumblr

Two arrays (example array1 and array2) contains the list of string. Write a program to find Intersection and union of Array Lists.

Algorithm Explanation

Construct two string arrays. Pass two array list objects to the utility function.
The union operation iterate each list and add to the hash set which do not allow duplicates.
The intersection operation creates the new list. It contains all the strings from both array list. If the string contains, add to the common string list.

Source Code

package com.dsacode.DataStructre.hashtable;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
 
public class UnionOfArrayLists {
     public < T > List < T > union( List < T > list1, List < T > list2) {
            Set < T > set = new HashSet < T >();
 
            set.addAll(list1);
            set.addAll(list2);
 
            return new ArrayList < T >(set);
        }
 
        public < T > List < T > intersection( List < T > list1, List < T > list2) {
            List < T > list = new ArrayList < T >();
 
            for (T t : list1) {
                if(list2.contains(t)) {
                    list.add(t);
                }
            }
 
            return list;
        }
    public static void main(String[] args) {
             
        List < String > list1 = new ArrayList < String >(Arrays.asList("A", "B", "C"));
        List < String > list2 = new ArrayList < String >(Arrays.asList("B", "C", "D", "E", "F"));
         
        System.out.println("Array 1 items: "+list1.toString());
        System.out.println("Array 2 items: "+list2.toString());
             
        System.out.println("Intersection of two arrays: "+new UnionOfArrayLists().intersection(list1, list2));
        System.out.println("Union of two arrays: "+new UnionOfArrayLists().union(list1, list2));
    }
 
}

Output

Array 1 items: [A, B, C]
Array 2 items: [B, C, D, E, F]
Intersection of two arrays: [B, C]
Union of two arrays: [A, B, C, D, E, F]

Write A Comment