Access values of hashmap
You can do it by using for loop
Set keys = map.keySet(); // It will return you all the keys in Map in the form of the Set
for (Iterator i = keys.iterator(); i.hasNext();)
{
String key = (String) i.next();
Records value = (Records) map.get(key); // Here is an Individual Record in your HashMap
}
You can use Map#entrySet
method, if you want to access the keys
and values
parallely from your HashMap
: -
Map<String, Records> map = new HashMap<String, Records> ();
//Populate HashMap
for(Map.Entry<String, Record> entry: map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
Also, you can override toString
method in your Record
class, to get String Representation of your instances
when you print them in for-each
loop.
UPDATE: -
If you want to sort your Map
on the basis of key
in alphabetical order, you can convert your Map
to TreeMap
. It will automatically put entries sorted by keys: -
Map<String, Integer> treeMap = new TreeMap<String, Integer>(map);
for(Map.Entry<String, Integer> entry: treeMap.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
For more detailed explanation, see this post: - how to sort Map values by key in Java