Map iterations in java

Iterate Map in java

There are different ways to iterate a map in java.
java.util.Map is an interface. There are various implementations of Map such as HashMap , TreeMap , LinkedHashMap .

All the methods outlined in this article can be used for iterating over any of these types.

Method 1 : forEach() java map
Starting java 8, forEach() method is added to java.util.Map interface. This method can be used to iterate through a hashmap.
In every iteration, it is supplied with two arguments, one is a key and another is the value of current map entry.
In the current example, we just print the key and value of the entry.

import java.util.HashMap; import java.util.Map; public class MapIterator < public static void main(String[] args) < // create a hashmap Mapmap = new HashMap(); // add values map.put(1, "mango"); map.put(2, "orange"); map.put(3, "guava"); map.forEach((key, value) -> < // print key System.out.println("Key: " + key); // print value System.out.println("Value: " + value); >); > >

forEach() method takes an argument of type java.util.function.BiConsumer which is a functional interface having a method which accepts two arguments.
Hence, we can supply a Lambda expression to forEach() method with two arguments which are the key and value of a map element.
If you print both key and value in a single statement, then curly braces in lambda expression can be omitted as shown below.

map.forEach((key, value) -> System.out.println("Key: " + key + ", value text-align: justify;">Above code prints

Key: 1, value= mango
Key: 2, value= orange
Key: 3, value= guava

Method 2: Using entrySet()
A map stores data in key-value pairs also known as entries. These entries are instances of type java.util.Map.Entry which is a nested interface of java.util.Map interface.

Each entry corresponds to a map element and contains key and value for that element with methods to retrieve them(getKey() and getValue()) and modify them(setKey() and setValue()).
Entries stored in a map can be retrieved by calling entrySet() method on the map. This set can then be iterated using a for loop as shown below.

import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class MapIterator < public static void main(String[] args) < // create a hashmap Mapmap = new HashMap(); // add values map.put(1, "mango"); map.put(2, "orange"); map.put(3, "guava"); // get all map entries Set> entrySet = map.entrySet(); // iterate over entries using a for loop for (Entry entry : entrySet) < // get key and value of each entry System.out.println("Key: "+entry.getKey()); System.out.println("Value: "+entry.getValue()); >> >

Key: 1
Value: mango
Key: 2
Value: orange
Key: 3
Value: guava

Note that the for loop used in this example is an enhanced for loop or a for-each loop.

Method 3 : Iterator on entrySet()
As discussed above, elements of a map are stored as entries and entrySet() method returns those entries in the form of a java.util.Set .
This set can also be iterated using a java.util.iterator .
A java iterator contains a hasNext() method which returns true if the set has an element to be iterated and a next() method that returns the set element at the current iterator position.
When next() is called, iterator moves on to the next element in the set. Example,

import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class MapIterator < public static void main(String[] args) < // create a hashmap Mapmap = new HashMap(); // add values map.put(1, "mango"); map.put(2, "orange"); map.put(3, "guava"); // get iterator over the map entries Iterator iterator = map.entrySet().iterator(); // iterate over entries using a loop while(iterator.hasNext()) < // get current map entry Entryentry = iterator.next(); // get key and value of each entry System.out.println("Key: "+entry.getKey()); System.out.println("Value: "+entry.getValue()); > > >

Output of above program is

Key: 1
Value: mango
Key: 2
Value: orange
Key: 3
Value: guava

Method 4 : keySet() and iterator
A map has a keySet() method which returns a java.util.Set of all the keys of the map. This set of keys can be iterated using a java.util.iterator .

In every iteration, the iterator’s next() method will return the key for a map entry. This key can be used to retrieve the corresponding value using get() method of the map.
get() method accepts a key for the map entry and returns the corresponding value. Example,

import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class MapIterator < public static void main(String[] args) < // create a hashmap Mapmap = new HashMap(); // add values map.put(1, "mango"); map.put(2, "orange"); map.put(3, "guava"); // get iterator over the keys of map Iterator iterator = map.keySet().iterator(); // iterate over map key while (iterator.hasNext()) < // get current map key Integer key = iterator.next(); System.out.println("Key: " + key); // get value of this key System.out.println("Value: " + map.get(key)); >> >

Remember that this method will search the entire map for the value of a key till it is found and is thus an inefficient method of iteration when compared to other methods described above.

Method 5 : Using Stream.of() java 8
A map can also be iterated using java 8 streams .
Stream provides a static of() method which accepts a collection and returns a stream over it.
Retrieve set of map entries using entrySet() method which returns a java.util.Set and pass it to Stream.of() method.
Now, you can easily iterate over this stream using forEach() method as shown below.

import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; public class MapIterator < public static void main(String[] args) < // create a hashmap Mapmap = new HashMap(); // add values map.put(1, "mango"); map.put(2, "orange"); map.put(3, "guava"); // iterate with Stream.of Stream.of(map.entrySet()).forEach(e -> < System.out.println(e); >); > >

Hope the article was useful.

Источник

Iterate Over a Map in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It's one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you'll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We're looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this quick tutorial, we'll look at the different ways of iterating through the entries of a Map in Java.

Simply put, we can extract the contents of a Map using entrySet(), keySet(), or values(). Since these are all sets, similar iteration principles apply to all of them.

Let's have a closer look at a few of these.

Further reading:

Guide to the Java 8 forEach

How to Iterate Over a Stream With Indices

Finding the Highest Value in a Java Map

2. Short Introduction to Map‘s entrySet(), keySet(), and values() Methods

Before we iterate through a map using the three methods, let's understand what these methods do:

  • entrySet() – returns a collection-view of the map, whose elements are from the Map.Entry class. The entry.getKey() method returns the key, and entry.getValue() returns the corresponding value
  • keySet() – returns all keys contained in this map as a Set
  • values() – returns all values contained in this map as a Set

3. Using a for Loop

3.1. Using entrySet()

First, let's see how to iterate through a Map using the EntrySet:

public void iterateUsingEntrySet(Map map) < for (Map.Entryentry : map.entrySet()) < System.out.println(entry.getKey() + ":" + entry.getValue()); >>

Here, we're extracting the Set of entries from our Map and then iterating through them using the classical for-each approach.

3.2. Using keySet()

Alternatively, we can first get all keys in our Map using the keySet method and then iterate through the map by each key:

public void iterateUsingKeySetAndForeach(Map map) < for (String key : map.keySet()) < System.out.println(key + ":" + map.get(key)); >>

3.3. Iterating Over Values Using values()

Sometimes, we're only interested in the values in a map, no matter which keys are associated with them. In this case, values() is our best choice:

public void iterateValues(Map map) < for (Integer value : map.values()) < System.out.println(value); >> 

4. Iterator

Another approach to perform the iteration is using an Iterator. Next, let's see how the methods work with an Iterator object.

4.1. Iterator and entrySet()

First, let's iterate over the map using an Iterator and entrySet():

public void iterateUsingIteratorAndEntry(Map map) < Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) < Map.Entryentry = iterator.next(); System.out.println(entry.getKey() + ":" + entry.getValue()); > >

Notice how we can get the Iterator instance using the iterator() API of the Set returned by entrySet(). Then, as usual, we loop through the Iterator with iterator.next().

4.2. Iterator and keySet()

Similarly, we can iterate through the Map using an Iterator and keySet():

public void iterateUsingIteratorAndKeySet(Map map) < Iteratoriterator = map.keySet().iterator(); while (iterator.hasNext()) < String key = iterator.next(); System.out.println(key + ":" + map.get(key)); >> 

4.3. Iterator and values()

We can also walk through the map's values using an Iterator and the values() method:

public void iterateUsingIteratorAndValues(Map map) < Iteratoriterator = map.values().iterator(); while (iterator.hasNext()) < Integer value = iterator.next(); System.out.println("value :" + value); >>

5. Using Lambdas and Stream API

Since version 8, Java has introduced the Stream API and lambdas. Next, let's see how to iterate a map using these techniques.

5.1. Using forEach() and Lambda

Like most other things in Java 8, this turns out to be much simpler than the alternatives. We'll just make use of the forEach() method:

public void iterateUsingLambda(Map map) < map.forEach((k, v) ->System.out.println((k + ":" + v))); > 

In this case, we don't need to convert a map to a set of entries. To learn more about lambda expressions, we can start here.

We can, of course, start from the keys to iterate over the map:

public void iterateByKeysUsingLambda(Map map) < map.keySet().foreach(k ->System.out.println((k + ":" + map.get(k)))); > 

Similarly, we can use the same technique with the values() method:

public void iterateValuesUsingLambda(Map map) < map.values().forEach(v ->System.out.println(("value: " + v))); > 

5.2. Using Stream API

Stream API is one significant feature of Java 8. We can use this feature to loop through a Map as well.

Stream API should be used when we're planning on doing some additional Stream processing; otherwise, it's just a simple forEach() as described previously.

Let's take entrySet() as the example to see how Stream API works:

public void iterateUsingStreamAPI(Map map) < map.entrySet().stream() // . some other Stream processings .forEach(e ->System.out.println(e.getKey() + ":" + e.getValue())); > 

The usage of Stream API with the keySet() and values() methods would be pretty similar to the example above.

6. Conclusion

In this article, we focused on a critical but straightforward operation: iterating through the entries of a Map.

We explored a couple of methods that can only be used with Java 8+, namely Lambda expressions and the Stream API.

As always, the code examples in this article can be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you'll have results within minutes:

Источник

Читайте также:  Php database connection with sql server
Оцените статью