The declaration of the HashMap is done as follows:
class HashMap< K, V >
where
K
is the datatype of Key and
V
is the datatype of the Value.
The
HashMap
supports 4 constructors:
The following examples uses
HashMap
and shows how to get key values in a map using
keySet
method.
HashMapDemo
import java.util.*;
class HashMapDemo
{
public static void main(String arg[])
{
HashMap<Character, Integer> asciicodemap = new HashMap<Character, Integer>();
asciicodemap.put('A', 65);
asciicodemap.put('B', 66);
asciicodemap.put('C', 67);
asciicodemap.put('D', 68);
asciicodemap.keySet();
System.out.println(asciicodemap.keySet());
}
}
DESCRIPTIONWe initially create a hash map with Character
as type key and Integer
as type value. We add the elements to the hash map asciicodemap
by usingput()
. Here the keyset
method returns a Set
view of the keys contained the map. Note that the output displayed is not in the order in which we entered into the map but in the order the iterator has read it.
THINGS TO TRY
- Try for the below code.
HashMap<Character, Integer> asciicodemap = new HashMap<Character, Integer>();
asciicodemap.put('A', 65);
asciicodemap.put('B', 66);
System.out.println(asciicodemap.get('A'));
The output for the above code will be 65
. We can get individual key values by using get
method.
- Try to use all the methods defined by
Map Interface
.
The below program shows how to get mappings using
entrySet
method.
The following is the syntax for the
entrySet
method.
public Set<Map.Entry<K,V>> entrySet();
HashMapDemo1
import java.util.*;
class UsingEntryset
{
HashMap<Character, Integer> asciicodemap = new HashMap<Character, Integer>();
asciicodemap.put('A', 65);
asciicodemap.put('B', 66);
asciicodemap.put('C', 67);
asciicodemap.put('D', 68);
Set<Map.Entry<Character, Integer>> st = asciicodemap.entrySet(); // LINE A
for (Map.Entry<Character, Integer> elements : st)
{
System.out.println("Key : " + elements.getKey() + ", Value : " + elements.getValue());
}
}
OUTPUTKey : D, Value : 68
Key : A, Value : 65
Key : B, Value : 66
Key : C, Value : 67
DESCRIPTIONHere we have used entrySet
method which returns a Set
view of mappings in a map at LINE A
. By using entrySet
method we can get both keys and values. Not that output displayed is not in the order in which we entered into the map but in the order the iterator has read it.
THINGS TO TRY
- Try for the below code.
HashMap<String, String> teamIndia = new HashMap<String, String>();
teamIndia.put("Batsmen", "Dhoni");
teamIndia.put("Bowler", "Zaheer Khan");
Set<Map.Entry<String, String>> entry = teamIndia.entrySet();
for (Map.Entry<String, String> elements : entry)
{
System.out.println("Key: " + elements.getKey() + " Value : " + elements.getValue());
}
The output must be as shown.
Key: Bowler Value : Zaheer Khan
Key: Batsmen Value : Dhoni
- Try for
<Character, Character>
, <Integer, Integer>
pairings in HashMap
.