Please disable your adblock and script blockers to view this page

Search this blog

Monday 3 August 2015

Iterate over HashMap to get Key and Value in Java , Add records to HashMap

Iterating over HashMap is not same as other collections , It's a bit tricky than normal iteration ;)
See in this code -
How to add values to HashMap ?
and How to iterate over HashMap to get Key and Values?

package client;

import java.util.HashMap;
import java.util.Iterator;

public class IterateHashMap {
    public IterateHashMap() {

    public static void main(String[] args) {
        HashMap<Integer, String> mapVal = new HashMap<Integer, String>();

        //Add values to Map
        mapVal.put(1, "value 1");
        mapVal.put(2, "value 2");
        mapVal.put(3, "value 3");
        mapVal.put(4, "value 4");

        //Create Iterator from keySet
        Iterator iter = mapVal.keySet().iterator();
        //Iterate over hashmap to get key
        while (iter.hasNext()) {
            int key = (Integer);
            //Use this key to find value
            String value = mapVal.get(key).toString();
            System.out.println("**KEY**  " + key + " AND VALUE**  " + value);


Cheers :) Happy Learning

No comments :

Post a Comment