集册 Java实例教程 从键和值列表创建映射。

从键和值列表创建映射。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

414
从键和值列表创建映射。
//from n o w j a   v  a . c o m - 时  代  Java


//package com.nowjava;

import java.util.HashMap;


import java.util.List;

import java.util.Map;


public class Main {

    /**

     * Create map from keys and values lists.

     * <p/>

     * <p/>

     * NB: Values with same keys will be overridden.

     *

     * @param keys   Lists of keys

     * @param values Lists of values

     * @param <K>    Keys type

     * @param <V>    Values type

     * @return Map generated from keys and values lists where key assigned with value which

     *         have same index

     * @throws IllegalArgumentException If keys or values are nulls or have different size

     */

    @SuppressWarnings({ "unchecked", "TypeMayBeWeakened" })

    public static <K, V> Map<K, V> createMap(final List<K> keys,

            final List<V> values)


    throws IllegalArgumentException {


        return createMap((K[]) keys.toArray(), (V[]) values.toArray());

    }


    /**

     * Create map from keys and values array.

     * <p/>

     * <p/>

     * NB: Values with same keys will be overridden.

     *

     * @param keys   Array of keys

     * @param values Array of values

     * @param <K>    Keys type

     * @param <V>    Values type

     * @return Map generated from keys and values array's where key assigned with value which

     *         have same index

     * @throws IllegalArgumentException If keys or values are nulls or have different size

     */

    public static <K, V> Map<K, V> createMap(final K[] keys,
    /** 
     来自 时代Java - N o w  J a v a . c o m**/

            final V[] values) throws IllegalArgumentException {


        if (keys == null || values == null || keys.length != values.length) {

            throw new IllegalArgumentException("Wrong arguments passed");

        }


        final Map<K, V> map = new HashMap<>(keys.length);


        for (int i = 0; i < keys.length; i++) {

            map.put(keys[i], values[i]);

        }


        return map;

    }


    /**

     * Create map from keys and values maps.

     * <p/>

     * <p/>

     * NB: Values with same keys will be overridden.

     *

     * @param keys   Map of keys

     * @param values Map of values

     * @param <I>    Indexes type

     * @param <K>    Keys type

     * @param <V>    Values type

     * @return Map generated from keys and values maps where key assigned with value which

     *         have same index (key for input maps)

     * @throws IllegalArgumentException If keys or values are nulls or have different size

     */

    public static <I, K, V> Map<K, V> createMap(final Map<I, K> keys,

            final 
展开阅读全文