Menu
Topics Index
...
`

HashMapDemo1 - Java Example Program


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());
    }
}
OUTPUT

Key : D, Value : 68
Key : A, Value : 65
Key : B, Value : 66
Key : C, Value : 67

DESCRIPTION

Here 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.

© meritcampus 2019

All Rights Reserved.

Open In App