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 (ornull
if there is no current mapping). For example, to either create or append aString
msg to a value mapping:map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))
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.
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 isnull
. This method may be of use when combining multiple mapped values for a key. For example, to either create or append aString 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 interfaceMap<K,V>
- Parameters:
key
- key with which the resulting value is to be associatedvalue
- 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 keyremappingFunction
- 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
'IT > java' 카테고리의 다른 글
[read] java call by reference call by value 레퍼런스 (2) | 2016.12.12 |
---|---|
숫자 판단 isdigit 는 아니지만... 문자 판단 (0) | 2016.09.08 |
json <-> map (0) | 2016.08.17 |
statements vs expressions (구문 vs 표현식) in lambda (0) | 2015.11.09 |
java 8 tutorial 한글 (2) | 2014.04.09 |