Determine the union of two ArrayList - Java Collection Framework

Java examples for Collection Framework:List

Description

Determine the union of two ArrayList

Demo Code


//package com.java2s;
import java.util.ArrayList;

public class Main {
    /**/*from  w w w  .ja v  a2  s  .  c o  m*/
     * Determine the union of two sets 
     * 
     * @param setA - the first of the two sets for the union
     * @param setB - the second of the two sets for the union 
     * @return a union between setA and setB
     * @throws java.lang.IllegalArgumentException - 
     *                  when one of setA or setB is null or empty 
     */
    public static ArrayList<Integer> union(ArrayList<Integer> setA,
            ArrayList<Integer> setB) throws IllegalArgumentException {
        ArrayList<Integer> returnValues = new ArrayList<Integer>();
        if (null == setA || null == setB) {
            throw new IllegalArgumentException(
                    "Arralist arguments cannot be null");
        }
        if (setA.size() == 0 || setB.size() == 0) {
            throw new IllegalArgumentException(
                    "Arraylist arguments cannot be empty");
        }

        for (int i = 0; i < setA.size(); i++) {
            boolean isAddable = true;
            for (int j = 0; j < returnValues.size() && isAddable; j++) {
                isAddable = setA.get(i) != returnValues.get(j);
            }
            if (isAddable) {
                returnValues.add(setA.get(i));
            }
        }

        for (int i = 0; i < setB.size(); i++) {
            boolean isAddable = true;
            for (int j = 0; j < returnValues.size() && isAddable; j++) {
                isAddable = setB.get(i) != returnValues.get(j);
            }
            if (isAddable) {
                returnValues.add(setB.get(i));
            }
        }

        return returnValues;
    }
}

Related Tutorials