1
class hello {
    string name;
    int number;
}

class object {
    public static void main(string args[]) {
        HashMap hs = new HashMap();
        hello c1 = new hello();
        hello c2 = new hello();
        hs.put("india",c1);
        hs.put("america",c2);
    }
}

how to print he key value pairs

key with multiple values how is it printed

takendarkk
  • 3,347
  • 8
  • 25
  • 37
lokesh
  • 13
  • 1
  • 3
  • `HashMap` has a perflecty fine `toString` representation if you override the `toString` method in your `hello` class. Also you should override `equals` and `hashcode`. – Alexis C. Mar 31 '14 at 17:05
  • 2
    *Don't* call a class `object`. Don't call it `Object`, too. –  Mar 31 '14 at 17:05
  • 1
    possible duplicate of [How can I iterate over a map of ?](http://stackoverflow.com/questions/3995463/how-can-i-iterate-over-a-map-of-string-pojo) – jmj Mar 31 '14 at 17:07

4 Answers4

1

Iterate Map or HashMap like this.

Map<String, Hello> map=new HashMap<>();
Set<Entry<String, Hello>> entries=map.entrySet();
for (Entry<String, Hello> entry : entries) {
    String key=entry.getKey();
    Hello hello=entry.getValue();
}
Sunil Singh Bora
  • 771
  • 9
  • 24
1

With Java 8:

map.forEach((key, value) -> System.out.println(key + ", " + value));
VH-NZZ
  • 5,248
  • 4
  • 31
  • 47
0

You need to iterate over hash map keys, then print the key with its value.

Example:

HashMap<String, hello> map = new HashMap<String, hello>();
    for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
        String key = iterator.next();
        System.out.println(key + map.get(keu).toString); suppose you already override the toString method in your hello class
    }
Salah
  • 8,567
  • 3
  • 26
  • 43
  • 1
    I think it's better to iterate through the `entrySet` directly because you don't need to recompute the hashcode each time you want the value associated with the key. Also the for each loop is your friend :) – Alexis C. Mar 31 '14 at 17:12
0

You can iterate using Entry Set too.

 HashMap<String,hello> hs=new HashMap<String, hello>();
 // Put values for hashMap.
 for(Map.Entry<String, hello> printPairs: hs.entrySet()) {
       System.out.print(printPairs.getKey()+" ---- ");
       System.out.println(printPairs.getValue());
  }
Vinayak Pingale
  • 1,315
  • 8
  • 19