How to iterate maps in Java.

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

public class MapTest {

    public static void main(String[] args) {
        Map<String, Integer> persons = new HashMap<String, Integer>();
        persons.put("Andy", 30);
        persons.put("Mike", 25);

        // use for - key
        for (String k: persons.keySet()) {
            System.out.println(k + " " + persons.get(k));
        }

        // use for - value
        for (Integer v: persons.values()) {
            System.out.println(v);
        }

        // use for - entry
        for (Map.Entry<String, Integer> entry: persons.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

        // use iterator
        Iterator<Map.Entry<String, Integer>> iter = persons.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Integer> p = iter.next();
            System.out.println(p.getKey() + " " + p.getValue());
        }

        // use lambda - java8
        persons.forEach((k, v) -> System.out.println(k + " " + v));

        // use streams - java8
        persons.entrySet().stream().forEach((entry) -> {
            System.out.println(entry.getKey() + " " + entry.getValue());
        });
    }
}
TOPâ–˛
Post tagged with: java