Adds an element to a map of List s. - Java java.util

Java examples for java.util:Map Entry

Description

Adds an element to a map of List s.

Demo Code

/*/*from  w w  w . j a v  a2  s .c om*/
 * Copyright 2013 Anton Karmanov
 *
 * Licensed 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.
 */
//package com.java2s;

import java.util.ArrayList;

import java.util.List;
import java.util.Map;

public class Main {
    /**
     * Adds an element to a map of {@link List}s. If there is no list in the map with the specified key,
     * a new one is put into the map.
     * 
     * @param map the map.
     * @param key the key for looking up a list.
     * @param value the value to be added to the list.
     */
    static <K, V> void addToListMap(Map<K, List<V>> map, K key, V value) {
        List<V> list = map.get(key);
        if (list == null) {
            list = new ArrayList<>();
            map.put(key, list);
        }
        list.add(value);
    }
}

Related Tutorials