Here you can find the source of addTo(Map
element
to the value-collection of key
in map
.
@SuppressWarnings({ "unchecked", "rawtypes" }) public static <N, E, C extends Collection> void addTo(Map<N, C> map, N key, E element, Class<? extends Collection> collectionClass)
//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); } }