0

I have users as my hashmap . How would I be able to display each value String from my hashmap using its key? Sample key: "1", Sample value: "name: flower" "age: 6". Is there simpler way for to display flower and 6?

     Iterator it = users.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pair = (Map.Entry)it.next();
                Log.e(pair.getKey().toString(), " = " + pair.getValue());
                it.remove(); // avoids a ConcurrentModificationException
            }
AndI
  • 3
  • 1
  • 2
  • 5

1 Answers1

1

As with most things, there are many ways this can be achieved. The simplest way I find that can iterate over the key/value pairs is as follows:

for (String key : map.keySet()) {
   System.out.println(key + " : " + map.get(key).toString());
}

Another similarly simplistic solution would be:

for (Map.Entry<String, User> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue().toString());
}

Just replace String with whatever the Class you have designated as the key.

Edit: If you are wanting to remove during the iteration, this solution would be inappropriate.

Zachary
  • 1,693
  • 1
  • 9
  • 13
  • what i get when I use this is somewhat like "User@4ffc4c8" – AndI Dec 16 '17 at 12:26
  • I think he wants to remove every entry after looping. This is not possible with your current implementation since this will yield a `ConcurrentModificationException`. – Martijn Dec 16 '17 at 12:27
  • @AndI What is the signature of your HashMap? Is it `Map` or `Map`? – Martijn Dec 16 '17 at 12:29
  • it's HashMap – AndI Dec 16 '17 at 12:30
  • The simplest way would be to iterate over the `entrySet` directly. – Marvin Dec 16 '17 at 12:35
  • The reason you would get something like "User@4ffc4c8" would be because you have not over-ridden the public String toString() method. Note map.get(key) returns an object reference associated to the key, so you can deal with the object as you wish. – Zachary Dec 16 '17 at 12:35
  • Thanks all. It went well when i iterated through the entry set value (which is an object in my hashmap). Something like this: users.get(key).getFullname().toString(). I forgot to went inside the object. Thanks All! – AndI Dec 16 '17 at 12:37
  • Not a problem. As @Martijn has noted, if you are wanting to remove during iteration this will throw a ConcurrentModificationException. Though if you are not wanting to remove, this is probably the most elegant solution. – Zachary Dec 16 '17 at 12:40