Java Array to Map toMap(K[] keys, V[] values)

Here you can find the source of toMap(K[] keys, V[] values)

Description

Creates a mutable map out of two arrays with keys and values.

License

Apache License

Declaration

public static <K, V> Map<K, V> toMap(K[] keys, V[] values) 

Method Source Code

//package com.java2s;
/*****************************************************************
 *   Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.//  w ww .j  a  va  2 s .c  o  m
 ****************************************************************/

import java.util.HashMap;

import java.util.Map;

public class Main {
    /**
     * Creates a mutable map out of two arrays with keys and values.
     *
     * @since 1.2
     */
    public static <K, V> Map<K, V> toMap(K[] keys, V[] values) {
        int keysSize = (keys != null) ? keys.length : 0;
        int valuesSize = (values != null) ? values.length : 0;

        if (keysSize == 0 && valuesSize == 0) {
            // return mutable map
            return new HashMap<>();
        }

        if (keysSize != valuesSize) {
            throw new IllegalArgumentException("The number of keys doesn't match the number of values.");
        }

        Map<K, V> map = new HashMap<>();
        for (int i = 0; i < keysSize; i++) {
            map.put(keys[i], values[i]);
        }

        return map;
    }
}

Related

  1. arrayToMap(int[] array)
  2. toMap(K[] keys, V[] values)
  3. toMap(String... args)
  4. toMap(String... keysAndValues)
  5. toMap(String[] keyNames, T[] values)