Java HashMap Counter increment(HashMap m, X key)

Here you can find the source of increment(HashMap m, X key)

Description

Increment the value associated with key by 1, or set it to 1 if there was no mapping for key

License

Open Source License

Parameter

Parameter Description
X a parameter
m a parameter
key a parameter

Return

the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)

Declaration

public static <X> Integer increment(HashMap<X, Integer> m, X key) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009, 2013, 2014 Matthew Purver, Queen Mary University of London.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl.html//ww  w  .  jav a2 s  .  c o m
 ******************************************************************************/

import java.util.HashMap;

public class Main {
    /**
     * Increment the value associated with key by 1, or set it to 1 if there was no mapping for key
     * 
     * @param <X>
     * @param m
     * @param key
     * @return the previous value associated with key, or null if there was no mapping for key. (A null return can also
     *         indicate that the map previously associated null with key.)
     */
    public static <X> Integer increment(HashMap<X, Integer> m, X key) {
        return m.put(key, ((m.get(key) == null) ? 1 : (m.get(key) + 1)));
    }
}

Related

  1. incrementHashMap(HashMap map, String key, int n)
  2. incrementMap(HashMap map, Integer key)
  3. incrementTwoLevelHashMap(HashMap map, String key1, String key2, int n)