简体   繁体   中英

Incrementing the value of a hashmap java

I have a hash map of places:

HashMap <String, Integer> places = new HashMap <String, Integer>();
places.put("London",0);
places.put("Paris",0);
places.put("dublin",0);

In this places I have a key of places and a value of how many times that place occurs in a text.

Say I have a texts:

  1. iloveLondon
  2. IamforLondon
  3. allaboutParis

Which are also stored in a hashmap:

 HashMap <String, Integer> text = new HashMap <String, Integer>();

I have a conditional statement to check if the place is in the text (where capitals and lower case is ignored:

for (String p: places):
{
   for(String t : text):
      if t.tolowercase().contains(p.tolowercase())
      {
        //then i would like to increment the value for places of the places hashmap
      }
}

In this example, the output should be: London, 2 Paris, 1 Dublin, 0

Ive got everything, except outputting the values and incrementing it, any suggestions?

To increment a value all you need to do is:

places.put("London",places.get("London")+1);

If the map does not contain "London" then the get will return a null, to handle that case you need to do:

Integer value = places.get("London");
if (value == null) {
   value = 1;
} else {
   value += 1;
}

places.put("London", value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM