[Java Basics] Let map value self-increment

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.