Java Tutorial Series - Collections - HashMap
In the series of Collection, we have already covered ArrayList, LinkedList, the difference between the two. Now we will be covering HashMap in this article.
HashMap Syntax -
HashMap<Integer,String> map = new Hashmap<Integer,String>();
map.put(5,"Five");
map.put(8,"Six");
map.put(4,"Four");
map.put("2","Two");
map.put("4","Hello");
String text = map.get(4);
System.out.println(text) // will give output "Hello"
For Loop for HashMap -
for(Map.Entry<Integer,String> entry: map.entrySet()) {
int key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ": " + value) ;
HashMap doesn't maintain any order as you would be able to see from the output. To overcome this issue, LinkedHashMap comes into play which has the same syntax as of HashMap.
Another way of using for loop in HashMap is shown below -
for(String key: map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
LinkedHashMap - It maintains the insertion order of elements.
TreeMap - TreeMap gives the output after sorting the key.
Another way of using for loop in HashMap is shown below -
for(String key: map.keySet()) {
System.out.println(key + ": " + map.get(key));
}
LinkedHashMap - It maintains the insertion order of elements.
TreeMap - TreeMap gives the output after sorting the key.
Comments
Post a Comment