from  http://codereview.stackexchange.com/questions/57078/more-elegant-way-to-increment-integers-in-map



map.merge(arr[11],1,(existValue,initValue) -> existValue+initValue);


위의 의미는 map 안에 arr[11] 의 키로 값이 없으면 1(initValue) 을 설정하고, 있으면 교체하기를 BiFunction 함수로 정의된대로 교체된다.

함수를 보면 existValue( 즉 arr[11] 에 있던 값) + initValue(arr[11] 다음에 정의된 값인 1 이다) 로 된다.

결과 처음에는 1 일테고, 다음에 또 해당 키로 put 이 들어오면 2가 되고(1+1이니까) 그 다음은 2+1 == 3 이 되고... 이런식이다. 



occurrences.compute(token, (tokenKey, oldValue) -> oldValue == null ? 1 : oldValue + 1);



아래는 javadoc


  • compute

    public V compute(K key,
                     BiFunction<? super K,? super V,? extends V> remappingFunction)
    Description copied from interface: Map
    Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). For example, to either create or append a String msg to a value mapping:
     
     map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))
    (Method merge() is often simpler to use for such purposes.)

    If the function returns null, the mapping is removed (or remains absent if initially absent). If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.

    Specified by:
    compute in interface Map<K,V>
    Parameters:
    key - key with which the specified value is to be associated
    remappingFunction - the function to compute a value
    Returns:
    the new value associated with the specified key, or null if none

  • merge

    public V merge(K key,
                   V value,
                   BiFunction<? super V,? super V,? extends V> remappingFunction)
    Description copied from interface: Map
    If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key. For example, to either create or append a String msg to a value mapping:
     
     map.merge(key, msg, String::concat)
     

    If the function returns null the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.

    Specified by:
    merge in interface Map<K,V>
    Parameters:
    key - key with which the resulting value is to be associated
    value - the non-null value to be merged with the existing value associated with the key or, if no existing value or a null value is associated with the key, to be associated with the key
    remappingFunction - the function to recompute a value if present
    Returns:
    the new value associated with the specified key, or null if no value is associated with the key


+ Recent posts