Requirements: I want to determine in the map whether there is a key, there is a key corresponding to the value = value+1, otherwise set <key,value=1>
The code is implemented in the following way:
ContainsKey
Import Java.util.HashMap; Import Java.util.Map, ..... MapNew hashmap<string, integer>(); .. int count = Freq.containskey (word)? Freq.get (Word): 0+ 1);
Testfornull
Import Java.util.HashMap; Import Java.util.Map, ..... MapNew hashmap<string, integer>= freq.get (word); if NULL ) { 1);} Else { + 1);}
Atomiclong
Import Java.util.concurrent.ConcurrentHashMap; Import Java.util.concurrent.ConcurrentMap; Import Java.util.concurrent.atomic.AtomicLong, ..... Final concurrentmap<string, atomiclong> map = new concurrenthashmap<string, atomiclong> New Atomiclong (0)); Map.get (word). Incrementandget ();
Trove
Import Gnu.trove.TObjectIntHashMap, ..... TobjectinthashmapNew tobjectinthashmap<string>1, 1);
Mutableint
ImportJava.util.HashMap;ImportJava.util.Map, .....classMutableint {intValue = 1;//Note that the We start at 1 since we ' re counting Public voidIncrement () {+ +value; } Public intGet () {returnvalue;}} ... Map<string, mutableint> freq =NewHashmap<string, mutableint>();... Mutableint Count=freq.get (word);if(Count = =NULL) {freq.put (Word,Newmutableint ());}Else{count.increment ();}
There are also ways to Java8:
Map.merge(key, 1, Integer::sum) //如果key存在,就调用sum 1 到map的value,如果key不存在,put(key,1)
< Span class= "pun" >< Span class= "PLN" > time, execute 1000 times, as shown below
Time , mskolobokecompile 18.8koloboke 19.8trove 20.8fastutil 22.7mutableint 24.3atomicinteger 25.3Eclipse 26.9 HashMap 28.0hppc 33.6hppcrt 36.5
[Java Basics] Let map value self-increment