Map Two Collections Together in Java

There are times where two separate entity object collections need to be mapped one-to-one.

The following code will combine two generic type collections together.

It also assesses the size of both collections and key uniqueness.

/**
 * Combines two generic type lists into a map.
 *
 * Detects key collisions and duplicate keys.
 *
 * @param keys a collection of objects
 * @param values another collection of objects the same size
 * as the key collection.
 * @return the combined map
 */
public static <K, V> Map<K, V> createMapFromCollections(  
        Collection<K> keys, Collection<V> values) {  

    Map<K, V> map = new HashMap<K, V>();
    Iterator<K> keyIterator = keys.iterator();
    Iterator<V> valueIterator = values.iterator();

    while (keyIterator.hasNext() && valueIterator.hasNext()) {
        K k = keyIterator.next();
        if (null != map.put(k, valueIterator.next())) {
            throw new IllegalArgumentException(
                    "Keys are not unique. Key "
                    + k + " is a duplicate.");
        }
    }

    if (keyIterator.hasNext() || valueIterator.hasNext()) {
        throw new IllegalArgumentException(
                "Key and value collections are not the same size");
    }

    return map;
}