Here you can find the source of addToMap(Map
public static <T> int addToMap(Map<Integer, T> map, int initialKey, T value)
//package com.java2s; /*/*from ww w . j a v a 2 s . c o m*/ * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Synacor, Inc. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software Foundation, * version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. * ***** END LICENSE BLOCK ***** */ import java.util.Map; public class Main { /** * Adds a value to the given <tt>Map</tt>. If <tt>initialKey</tt> already * exists in the map, uses the next available index instead. This way we * guarantee that we don't lose data if the client sends two elements with * the same index, or doesn't specify the index at all. * * @return the index used to insert the value */ public static <T> int addToMap(Map<Integer, T> map, int initialKey, T value) { int i = initialKey; while (true) { if (!map.containsKey(i)) { map.put(i, value); return i; } i++; } } }