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

Java examples for java.util:Map Entry

Description

Adds an element to a map of Set s.

Demo Code

/*//from w w  w  .j a va 2 s  . com
 * 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.HashSet;

import java.util.Map;
import java.util.Set;

public class Main {
    /**
     * Adds an element to a map of {@link Set}s. If there is no set 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 set.
     * @param value the value to be added to the set.
     */
    static <K, V> void addToSetMap(Map<K, Set<V>> map, K key, V value) {
        Set<V> set = map.get(key);
        if (set == null) {
            set = new HashSet<>();
            map.put(key, set);
        }
        set.add(value);
    }
}

Related Tutorials