In this post, we will see how to declare and use map, and also fetch the data from map.
Data can be represented in terms of key value pair
A map cannot have duplicate keys
Each key can contain one value and the value can be of any object from Integer to string and also could be arrays
#1
One simple map structure where we will declare key with values and the way we fetch the data
import java.util.HashMap; import java.util.Map; public class HashMapTest { public static void main(String[] args) { Map<String, Integer> hm = new HashMap(); hm.put("One", 123); hm.put("Two", 456); hm.put("Three", 789); for(Map.Entry map: hm.entrySet()) { System.out.println("Key - " + map.getKey() + " | Value - " + map.getValue()); } } }
In the above example, you can see the key data type is String and values should be Integer
Under the for condition section, hm.entrySet() fetches both the key and value
if you want to only fetch keys, then use
System.out.println("Keys from map - "); for(String key: hm.keySet()) { System.out.println("Key - " + key); }
if you want to only fetch values, then use
System.out.println("values from map - "); for(Integer value: hm.values()) { System.out.println("Value - " + value); }
#2
We will use the same map example from #1, but will fetch the data using iterator,
To know basics of iterator and how to fetch the data from a list, refer Iterator in list
System.out.println("Fetch map data using iterator"); Iterator it = hm.entrySet().iterator(); while(it.hasNext()) { Map.Entry entry = (Entry) it.next(); String Key = (String) entry.getKey(); Integer Value = (Integer) entry.getValue(); System.out.println("Key - " + Key + " | Value - " + Value); }
entrySet() basically returns a set, so we can use Iterator to fetch the data from the set and then fetch the key and value usual way.
#3
In the above example, we have seen one value with respect to a key, but we can have array of object like integer array or string array as values with respect to each key, so we will see how to declare the hashmap and then fetch each value
public class HashMapArray { public static void main(String[] args) { Map<String, Integer[]> hm = new HashMap(); hm.put("One", new Integer[] {12, 34}); hm.put("Two", new Integer[] {56, 78, 90}); for(Map.Entry map:hm.entrySet()) { Integer[] values = (Integer[]) map.getValue(); System.out.println("values corresponding to key " + map.getKey()); for(Integer item : values) System.out.print(item + " "); System.out.println(); } } }