Java Collection Union union(final Collection a, final Collection b)

Here you can find the source of union(final Collection a, final Collection b)

Description

union

License

Open Source License

Declaration

@SuppressWarnings({ "rawtypes", "unchecked" })
    public static Collection union(final Collection a, final Collection b) 

Method Source Code

//package com.java2s;
/**//from  w  ww .  ja v  a 2s  .  co m
 * License: src/main/resources/license/escidoc.license
 */

import java.util.ArrayList;
import java.util.Collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;

import java.util.Map;
import java.util.Set;

public class Main {
    private static Integer INTEGER_ONE = new Integer(1);

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Collection union(final Collection a, final Collection b) {
        ArrayList list = new ArrayList();
        Map mapa = getCardinalityMap(a);
        Map mapb = getCardinalityMap(b);
        Set elts = new LinkedHashSet(a);
        elts.addAll(b);
        Iterator it = elts.iterator();
        while (it.hasNext()) {
            Object obj = it.next();
            for (int i = 0, m = Math.max(getFreq(obj, mapa), getFreq(obj, mapb)); i < m; i++) {
                list.add(obj);
            }
        }
        return list;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map getCardinalityMap(final Collection coll) {
        Map count = new HashMap();
        for (Iterator it = coll.iterator(); it.hasNext();) {
            Object obj = it.next();
            Integer c = (Integer) (count.get(obj));
            if (c == null) {
                count.put(obj, INTEGER_ONE);
            } else {
                count.put(obj, new Integer(c.intValue() + 1));
            }
        }
        return count;
    }

    @SuppressWarnings({ "rawtypes" })
    private static final int getFreq(final Object obj, final Map freqMap) {
        Integer count = (Integer) freqMap.get(obj);
        if (count != null) {
            return count.intValue();
        }
        return 0;
    }
}

Related

  1. union(Collection a, Collection b)
  2. union(Collection c1, Collection c2)
  3. union(Collection initial, Collection other)
  4. union(Collection lhs, Collection rhs)
  5. union(Collection set1, Collection set2)
  6. union(final Collection c1, final Collection c2)
  7. union(final Collection... sets)
  8. union(final Collection a, final Collection b)
  9. unionAll(final Collection collector, final T[] a, final T[] b)