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

Java examples for java.util:Map Entry

Description

Adds an element to a map of Collection s.

Demo Code

/*//from  w  w  w . j  av  a  2 s. co  m
 * 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.Collection;

import java.util.Map;

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

Related Tutorials