We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Hash Map: Increase one value by 1
Page Index Toggle Pages: 1
Hash Map: Increase one value by 1 (Read 1543 times)
Hash Map: Increase one value by 1
Mar 13th, 2010, 3:51pm
 
Hello,

I have a list of String-values list.
I have a Hash Map hm.
When the String list[i] is not in hm, hm gets a new entry called list[i], value 1.  
When list[i] is already in hm: In hm I want to increase the value of list[i] that appears in hm.
But I can't get the value from hm...

Any help appreciated!  Cry

Chrisir  Wink


       if (hm.containsKey(list[i])) {
         Map.Entry me = (Map.Entry)hm.get(list[i]) ; // i.next();
         int OldValue  =int (me.getValue());
         hm.put(list[i], OldValue+1);
       }
       else {
         hm.put(list[i], 1);          
       }
Re: Hash Map: Increase one value by 1
Reply #1 - Mar 14th, 2010, 12:29am
 
Code:
HashMap hm = new HashMap();
String[] list = { "a", "b", "c", "a", "c", "a", "b", "a", "b" };
for (int i = 0; i < list.length; i++)
{
 Integer val = (Integer) hm.get(list[i]);
 if (val == null)
 {
   hm.put(list[i], 1);
 }
 else
 {
   hm.put(list[i], val + 1);
 }
}
println(hm);

I use a bit of "magic" of Java 1.5, which is able to automatically convert, when needed, Integer to int and back (auto-boxing).
Note also that instead of checking if a key is there then getting it, I just get it and see if I have a result: it is simpler and faster.
Re: Hash Map: Increase one value by 1
Reply #2 - Mar 15th, 2010, 2:30am
 
Hello!

Oh, that helped me a lot.

That could easily be added to the help-section of HashMap.

Greetings, Chrisir    Wink  



Re: Hash Map: Increase one value by 1
Reply #3 - Mar 17th, 2010, 2:01am
 

Hello,

I have an additional question.

How much can a HashMap take?

Let's say 400'000 entries with each 9 Letters in the key and value between -9000 and +9000?

What happens when I put too many entries in?

Greetings, Chris    Wink
Re: Hash Map: Increase one value by 1
Reply #4 - Mar 17th, 2010, 2:20am
 
should be ok, is limited by your memory more than anything in the code.
Re: Hash Map: Increase one value by 1
Reply #5 - Mar 17th, 2010, 4:06am
 
The question is interesting. koogy's answer is accurate, but I was curious.
Look at the source of HashMap (available with the JDK), I see:
static final int MAXIMUM_CAPACITY = 1 << 30;
That's 1,073,741,824...
Re: Hash Map: Increase one value by 1
Reply #6 - Mar 17th, 2010, 5:13am
 


should be ok (for now Roll Eyes)
Page Index Toggle Pages: 1