Creates a mapping from two arrays, one with keys, one with values. - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

Creates a mapping from two arrays, one with keys, one with values.

Demo Code

/* ******************************************************************************
 * Copyright (c) 2006-2013 XMind Ltd. and others.
 *
 * This file is a part of XMind 3. XMind releases 3 and
 * above are dual-licensed under the Eclipse Public License (EPL),
 * which is available at http://www.eclipse.org/legal/epl-v10.html
 * and the GNU Lesser General Public License (LGPL),
 * which is available at http://www.gnu.org/licenses/lgpl.html
 * See http://www.xmind.net/license.html for details.
 *
 * Contributors:/*  w  w w  .  jav a 2s .c o m*/
 *     XMind Ltd. - initial API and implementation
 *******************************************************************************/
//package com.java2s;

import java.util.LinkedHashMap;

import java.util.Map;

public class Main {
    /**
     * Creates a mapping from two arrays, one with keys, one with values.
     *
     * @param <K>
     *            Data type of the keys.
     * @param <V>
     *            Data type of the values.
     * @param keys
     *            Array containing the keys.
     * @param values
     *            Array containing the values.
     * @return Map with keys and values from the specified arrays.
     */
    public static <K, V> Map<K, V> map(K[] keys, V[] values) {
        // Check for valid parameters
        if (keys.length != values.length) {
            throw new IllegalArgumentException("Cannot create a Map: " //$NON-NLS-1$
                    + "The number of keys and values differs."); //$NON-NLS-1$
        }
        // Fill map with keys and values
        Map<K, V> map = new LinkedHashMap<K, V>();
        for (int i = 0; i < keys.length; i++) {
            K key = keys[i];
            V value = values[i];
            map.put(key, value);
        }
        return map;
    }
}

Related Tutorials