Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

public class Main {

    @SuppressWarnings("unchecked")
    public static <E> Collection<E> union(Collection<E> collectionA, Collection<E> collectionB) {
        Collection<E> collectionC = null;
        try {
            collectionC = collectionA.getClass().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return collectionC;
        }
        Iterator<E> aIterator = collectionA.iterator();
        Iterator<E> bIterator = collectionB.iterator();
        while (aIterator.hasNext() || bIterator.hasNext()) {
            if (aIterator.hasNext()) {
                E ae = aIterator.next();
                if (!collectionC.contains(ae)) {
                    collectionC.add(ae);
                }
            }
            if (bIterator.hasNext()) {
                E be = bIterator.next();
                if (!collectionA.contains(be) && !collectionC.contains(be)) {
                    collectionC.add(be);
                }
            }
        }
        return collectionC;
    }

    @SuppressWarnings("unchecked")
    public static <E> Map<String, E> union(Map<String, E> mapA, Map<String, E> mapB) {
        Map<String, E> mapC = null;
        try {
            mapC = mapA.getClass().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return mapC;
        }
        Iterator<String> akeys = mapA.keySet().iterator();
        Iterator<String> bkeys = mapB.keySet().iterator();
        while (akeys.hasNext() || bkeys.hasNext()) {
            if (akeys.hasNext()) {
                String ak = akeys.next();
                mapC.put(ak, mapA.get(ak));
            }
            if (bkeys.hasNext()) {
                String bk = bkeys.next();
                E e = mapB.get(bk);
                if (!mapA.containsKey(bk) || !mapA.get(bk).equals(e)) {
                    mapC.put(bk, mapA.get(e));
                }
            }
        }
        return mapC;
    }
}