Retrieving hashmap values in java

33,998

Solution 1

You are calling next() two times.

Try this instead:

while(i.hasNext())
{
    Entry e = i.next();
    String key = e.getKey();  
    String value = e.getValue();
    System.out.println(key + " " + value);
}

In short you could also use the following code (which also keeps the type information). Using Iterator is pre-Java-1.5 style somehow.

for(Entry<String, String> entry : facilities.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key + " " + value);
}

Solution 2

The problem is you're calling i.next() to get the key, then you call it again to get the value (the value of the next entry).

Another problem is you use toString on the one of the Entry's, which is not the same as getKey or getValue.

You need to do something like:

Iterator<Entry<String, String>> i = facilities.entrySet().iterator();
...
while (...)
{
   Entry<String, String> entry = i.next();
   String key = entry.getKey();  
   String value = entry.getValue();
   ...
}
Share:
33,998
Neil
Author by

Neil

Updated on July 09, 2022

Comments

  • Neil
    Neil almost 2 years

    I wrote below code to retrieve values in hashmap. But it didnt work.

    HashMap<String, String> facilities = new HashMap<String, String>();
    
    Iterator i = facilities.entrySet().iterator();
    
    while(i.hasNext())
    {
        String key = i.next().toString();  
        String value = i.next().toString();
        System.out.println(key + " " + value);
    }
    

    I modified the code to include SET class and it worked fine.

    Set s= facilities.entrySet();
    Iterator it = facilities.entrySet().iterator();
    while(it.hasNext())
    {
        System.out.println(it.next());
    }
    

    Can anyone guide me what went wrong in above code without SET class??

    P.S - I do not have much programming exp and started using java recently

    • Prateek
      Prateek over 11 years
      what error are you getting with the hashmap, i.e what is displayed ?
    • Behe
      Behe over 11 years
      What did you expect and what did you experience instead?
    • Neil
      Neil over 11 years
      I am not getting any error. But nothing gets displayed in the output screen. So i googled and used SET class instead. Then it displayed the values. So my question is why didnt it display the value without SET class?
  • Kai
    Kai over 11 years
    This will not result in the best performance. And this code is more difficult to read in my opinion.