Java Map Add addTo(Map map, N key, E element, Class collectionClass)

Here you can find the source of addTo(Map map, N key, E element, Class collectionClass)

Description

Adds element to the value-collection of key in map.

License

Apache License

Declaration

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <N, E, C extends Collection> void addTo(Map<N, C> map, N key, E element,
        Class<? extends Collection> collectionClass) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.Collection;

import java.util.Map;

public class Main {
    /**//www.  ja v a2s.  c o m
     * Adds <code>element</code> to the value-collection of <code>key</code> in <code>map</code>.
     * If <code>key</code> does not exist in <code>map</code> yet, a new collection of type
     * <code>collectionClass</code> will be instantiated, inserted in <code>map</code> with
     * the specified <code>key</code>, and <code>element</code> will be added to it.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static <N, E, C extends Collection> void addTo(Map<N, C> map, N key, E element,
            Class<? extends Collection> collectionClass) {
        C collection = map.get(key);
        if (collection == null) {
            try {
                collection = (C) collectionClass.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
            map.put(key, collection);
        }
        collection.add(element);
    }
}

Related

  1. addOne(Map map, K key)
  2. addOne(Map map, T key)
  3. addTo(Map> map, K key, T value)
  4. addToAnd(T target, Map... items)
  5. addToList(Map> map, X key, Y value)
  6. addToListMap(Map map, Object key, Object value)
  7. addToListMap(Map> map, K key, V value)