Java hashmap foreach example

How to iterate a HashMap in Java

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2023 with this popular free course.

There are several ways to iterate a HashMap in Java. However, the three listed below are the most common.

Three ways to iterate a Hashmap

  1. Using a for loop to iterate through a HashMap
  2. Using a forEach to iterate through a HashMap
  3. Using an iterator to iterate through a HashMap

1. Using a for loop to iterate through a HashMap

In the code below, hash_map.entrySet() is used to return a set view of the mapped elements. Now, getValue() and getKey() functions, key-value pairs can be iterated.

// importing library.
import java.util.HashMap;
import java.util.Map;
// class for iterating HashMap.
public class Iterate
public static void main(String[] arguments)
// creating HashMap.
Map hash_map = new HashMap();
// inserting sets.
hash_map.put(1, "Thor");
hash_map.put(2, "Iron man");
// iterating using for loop.
for (Map.Entry set : hash_map.entrySet())
System.out.println(set.getKey() + " = " + set.getValue());
>
>
>

2. Using a forEach to iterate through a HashMap

In the code below, the forEach function is used to iterate the key-value pairs.

// importing libraries.
import java.util.HashMap;
import java.util.Map;
// class for iterating HashMap.
public class Iterate
public static void main(String[] arguments)
// creating hash_map.
Map hash_map = new HashMap();
// inserting sets in the hash_map.
hash_map.put(1, "Thor");
hash_map.put(2, "Iron man");
// iterating it using forEach.
hash_map.forEach((key,value) -> System.out.println(key + " = " + value));
>
>

3. Using an iterator to iterate through a HashMap

In the code below, an iterator is used to iterate the each mapped pair.

// importing java libraries.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
// class for iterating HashMaps.
public class Iterate
public static void main(String[] arguments)
// creating hash_map.
Map hash_map = new HashMap();
// inserting value.
hash_map.put(1, "Thor");
hash_map.put(2, "Iron man");
// setting up iterator.
Iterator it = hash_map.entrySet().iterator();
// iterating every set of entry in the HashMap.
while (it.hasNext())
Map.Entry set = (Map.Entry) it.next();
System.out.println(set.getKey() + " = " + set.getValue());
>
>
>

Learn in-demand tech skills in half the time

Источник

HashMap iteration in Java

HashMap iteration in Java tutorial shows how to iterate over a HashMap in Java.

Java HashMap

is a container that stores key-value pairs. Each key is associated with one value. Keys in a HashMap must be unique. HashMap is called an associative array or a dictionary in other programming languages. HashMaps take more memory because for each value there is also a key. Deletion and insertion operations take constant time. HashMaps can store null values.

represents a key-value pair in HashMap . HashMap’s entrySet returns a Set view of the mappings contained in the map. A set of keys is retrieved with the keySet method.

HashMap iteration with forEach()

In the first example, we use Java 8 forEach method to iterate over the key-value pairs of the HashMap . The forEach method performs the given action for each element of the map until all elements have been processed or the action throws an exception.

package com.zetcode; import java.util.HashMap; import java.util.Map; public class HashMapForEach < public static void main(String[] args) < Mapitems = new HashMap<>(); items.put("coins", 5); items.put("pens", 2); items.put("chairs", 7); items.forEach((k, v) -> < System.out.format("key: %s, value: %d%n", k, v); >); > >

In the code example, we iterate over a HashMap with forEach using a lambda expression.

Map items = new HashMap<>(); items.put("coins", 5); items.put("pens", 2); items.put("chairs", 7);

A HashMap is created with a couple of pairs.

The forEach makes the code more concise.

HashMap iteration with Stream API

is a sequence of elements from a source that supports sequential and parallel aggregate operations. The source can be a collection, IO operation, or array, which provides data to a stream.

package com.zetcode; import java.util.HashMap; public class HashMapStreamApi < public static void main(String[] args) < HashMapitems = new HashMap<>(); items.put("coins", 5); items.put("pens", 2); items.put("chairs", 7); items.entrySet().stream().forEach(e -> < System.out.format("key: %s, value: %d%n", e.getKey(), e.getValue()); >); > >

The example iterates over a HashMap with the stream API. We get the entry set with entrySet method and from the entry set, we get the stream with the stream method. Later, we iterate over the stream with forEach .

HashMap iteration with enhanced for loop

Enhanced for loop, introduced in Java 5, can be used to iterate over a HashMap .

package com.zetcode; import java.util.HashMap; import java.util.Map; public class HashMapEnhancedFor < public static void main(String[] args) < HashMapitems = new HashMap(); items.put("coins", 5); items.put("pens", 2); items.put("chairs", 7); for (Map.Entry pair: items.entrySet()) < System.out.format("key: %s, value: %d%n", pair.getKey(), pair.getValue()); >> >

In the example, we iterate over a HashMap with enhanced for loop.

for (Map.Entry pair: items.entrySet())

In each for cycle, a new key-value couple is assigned to the pair variable.

HashMap iteration with Iterator

In the following example, we iterate over a HashMap with Iterator and Map.Entry .

package com.zetcode; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapIterator < public static void main(String[] args) < Mapitems = new HashMap<>(); items.put("coins", 5); items.put("pens", 2); items.put("chairs", 7); Iterator it = items.entrySet().iterator(); while (it.hasNext()) < Map.Entrypair = it.next(); System.out.format("key: %s, value: %d%n", pair.getKey(), pair.getValue()); > > >

In the code example we retrieve an iterator over the key-value pairs and iterate over the mappings in the while loop.

Iterator> it = items.entrySet().iterator();

We get the iterator object. First, we get the entry set with the entrySet method and from the entry set we get the iterator with iterator method.

The iterator’s hasNext method returns true if the iteration has more elements.

The next method returns the next pair.

System.out.format("key: %s, value: %d", pair.getKey(), pair.getValue());

With getKey and getValue methods we get the key and the value of the pair.

The following example is the same but uses a for loop instead of while.

package com.zetcode; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapIterator2 < public static void main(String[] args) < Mapitems = new HashMap<>(); items.put("coins", 5); items.put("pens", 2); items.put("chairs", 7); for (Iterator it = items.entrySet().iterator(); it.hasNext();) < Map.Entrypair = it.next(); System.out.format("key: %s, value: %d%n", pair.getKey(), pair.getValue()); > > >

In the example, we iterate over a HashMap with an iterator and for loop.

In the next example, we iterate over a key set with an iterator while using HashMap’s keySet method, which returns a Set view of the keys contained in this map. This iteration is less efficient.

package com.zetcode; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapIterator3 < public static void main(String[] args) < Mapitems = new HashMap<>(); items.put("coins", 5); items.put("pens", 2); items.put("chairs", 7); Iterator it = items.keySet().iterator(); while (it.hasNext()) < String key = it.next(); System.out.format("key: %s, value: %d%n", key, items.get(key)); >> >

In the example, we iterate over the key set of the map with an iterator. The iterator is used in a while loop to go over the keys of the map. The key is later used to get the corresponding value.

Iterator it = items.keySet().iterator();

We get the iterator object of the key set.

In the while loop, we traverse over the keys of the HashMap .

The next key is retrieved.

System.out.format("key: %s, value: %d%n", key, items.get(key));

The value is retrieved with the get method.

HashMap iteration over keys

We may need to iterate only over keys of a HashMap .

package com.zetcode; import java.util.HashMap; import java.util.Map; import java.util.Set; public class HashMapKeys < public static void main(String[] args) < Mapitems = new HashMap<>(); items.put("coins", 5); items.put("pens", 2); items.put("chairs", 7); Set keys = items.keySet(); keys.forEach(System.out::println); > >

The example iterates over keys of a HashMap .

The keys of a HashMap are retrieved with the keySet method, which returns a Set of keys. Keys must be unique; therefore, we have a Set . Set is a collection that contains no duplicate elements.

keys.forEach(System.out::println);

We go over the set of keys with forEach .

HashMap iteration over values

We may need to iterate only over values of a HashMap .

package com.zetcode; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class HashMapValues < public static void main(String[] args) < Mapitems = new HashMap<>(); items.put("coins", 5); items.put("pens", 2); items.put("chairs", 7); Collection vals = items.values(); vals.forEach(System.out::println); > >

The example iterates over values of a HashMap .

Collection vals = items.values();

The values of a HashMap are retrieved with the values method.

vals.forEach(System.out::println);

We go over the collection with forEach .

Iteration over HashMap containing ArrayList

A HashMap can contain lists as values. In such a case, we need an additional loop.

package com.zetcode; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class HashMapList < public static void main(String[] args) < Map> m = new HashMap<>(); m.put("colours", Arrays.asList("red", "green", "blue")); m.put("sizes", Arrays.asList("small", "medium", "big")); for (Map.Entry> me : m.entrySet()) < String key = me.getKey(); Listvalues = me.getValue(); System.out.println("Key: " + key); System.out.print("Values: "); for (String e : values) < System.out.printf("%s ", e); >System.out.println(); > > >

In the example, we iterate over a HashMap that contains ArrayLists as values. We use two for loops.

Map> m = new HashMap<>(); m.put("colours", Arrays.asList("red", "green", "blue")); m.put("sizes", Arrays.asList("small", "medium", "big"));

We define a HashMap having ArrayLists as values.

for (Map.Entry> me : m.entrySet()) 

With enhanced for loop, we go through the entry set. Each entry has a key string and list value.

We get the key with getKey method.

We get the list with getValue .

In the inner for loop, we iterate over the list of values.

HashMap filtering

HashMap can be filtered with the filter method of the Stream API.

package com.zetcode; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; public class HashMapFilter < public static void main(String[] args) < Mapcapitals = new HashMap<>(); capitals.put("svk", "Bratislava"); capitals.put("ger", "Berlin"); capitals.put("hun", "Budapest"); capitals.put("czk", "Prague"); capitals.put("pol", "Warsaw"); capitals.put("ita", "Rome"); Map filteredCapitals = capitals.entrySet().stream() .filter(map -> map.getValue().startsWith("B")) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); filteredCapitals.entrySet().forEach(System.out::println); > >

In the example, we have a map of countries with their capitals. We filter the map to contain only pairs whose values begin with B.

In this article we have shown how to iterate over a HashMap in Java.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

Читайте также:  Implement all abstract methods java
Оцените статью