Loading...
Logo
Processing Forum

HashMap: getKey()

in Programming Questions  •  10 months ago  
Is there a way to return the key for a HashMap as an integer? I used integers as the key and I'm trying to get integers back when I call getKey() but it returns objects.

Replies(5)

Re: HashMap: getKey()

10 months ago
I think this gets it done...

int eger = Integer.parseInt(data.getKey().toString());

Get the key, convert to string, then convert to int.

Re: HashMap: getKey()

10 months ago
Have you tried generics?

Copy code
  1. import java.util.*;
  2. import java.util.Map.Entry;

  3. Map<Integer, String> m = new HashMap<Integer, String>();

  4. m.put(1,"one");
  5. m.put(2,"two");
  6. m.put(3,"three");

  7. for (Entry<Integer,String> entry : m.entrySet()) {
  8.     int k = entry.getKey();    
  9.     String v = entry.getValue();
  10.     println(k+" is "+v);
  11. }

Re: HashMap: getKey()

10 months ago
Ok, I ran across another problem and I tested the same thing in your equation just to see if it would make a difference. How can I remove a value/key from the HashMap within a loop without getting this "ConcurrentModificationException"?
Copy code
  1. import java.util.*;
  2. import java.util.Map.Entry;

  3. Map<Integer, String> m = new HashMap<Integer, String>();
  4. m.put(1, "one");
  5. m.put(2, "two");
  6. m.put(3, "three");

  7. for (Entry<Integer,String> entry : m.entrySet()) {
  8.   int k = entry.getKey();   
  9.   String v = entry.getValue();
  10.   println(k+" is "+v);
  11.   m.remove(k);
  12. }

Re: HashMap: getKey()

10 months ago
In this case you can use an iterator instead of a foreach loop. An iterator allows to remove elements while cycling through the entryset whereas a foreach loop doesn't. 


Copy code
  1. import java.util.*;
  2. import java.util.Map.Entry;

  3. Map<Integer, String> m = new HashMap<Integer, String>();

  4. m.put(1,"one");

  5. m.put(2,"two");

  6. m.put(3,"three");

  7. println( "size of map (start) : " + m.size() );

  8. Iterator<Entry<Integer,String>> iter = m.entrySet().iterator();

  9. while (iter.hasNext()) {
  10.     Entry<Integer,String> entry = iter.next();
  11.     int k = entry.getKey();    
  12.     String v = entry.getValue();
  13.     println(k+" is "+v);
  14.     iter.remove();
  15. }

  16. println( "size of map (end)  : " + m.size() );

Re: HashMap: getKey()

10 months ago
Thank you very much good sir.