Home > Java > javaTutorial > body text

Java Iterate Map

王林
Release: 2024-08-30 16:07:50
Original
807 people have browsed it

Iterate Map is extracting a bunch of data from the Map collection. In most real-time cases, we have much data stored on a map. The developer wants to fetch this data; he has to iterate the entire map. A map is stored in util.Map package. In this topic, we are going to learn about Java Iterate Map.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

You can iterate over a map in 3 ways.

  • forEach
  • Normal for loop
  • While looping with an iterator

What is a Map?

1. Map is a key and value pair structured collection. The map is an interface. So, Map implemented into

  • HashMap
  • LinkedHashMap
  • TreeMap

2. Entry is the sub interface of Map. Therefore, it will be accessible by the Entry name. It returned the collection view of the map. Map. The entry provides methods to fetch key and value pair.

Important Methods

  • put(Object keyValue, Object objectValue): It inserts some value into a map.
  • keySet(): It is used for getting a key pair set.
  • entrySet(): It is used to set keys and values to the map.
  • size(): It is used for getting map size.
  • getKey(): It is used for getting a key value.
  • getValue(): It is used for getting a key-mapped value.

How Does Iteration Work in Map?

As discussed above, Map can be iterated with forEach, normal for, and while loop. We will understand it by Syntax.

1. forEach

Syntax:

Map<DataType, DataType>map = new HashMap<DataType, DataType>();
map.forEach((key, value) -> //logic
Copy after login

2. for with entrySet()

Syntax:

Map<DataType,DataType> map= new HashMap<DataType,DataType>();
for (Map.Entry<DataType,DataType> set: map.entrySet())
//logic
}
Copy after login

3. While loop with an iterator

Syntax:

Map<String, String> mapObj = new HashMap<>();
Iterator iterator= mapObj .entrySet().iterator();
while (iterator.hasNext()) {
//logic
}
Copy after login

Based on the requirement, we can iterate the map in any of the above ways.

Examples of Java Iterate Map

Given below are the examples:

1. Map iteration with forEach Example

Code:

import java.util.HashMap;
import java.util.Map;
public class ForEachMapIteration {
public static void main(String[] args) {
// creating a hashmap object
Map<Integer, String> names = new HashMap<>();
// adding key and values to hash map
names.put(1, "Paramesh");
names.put(2, "Amardeep");
names.put(3, "Venkatesh");
names.put(4, "Ramesh");
names.put(5, "Suresh");
names.put(3, "Krishna");
names.put(4, "Rama");
names.put(5, "Rajitha");
// iterating key and value with forEach loop
names.forEach((key, value) -> {
System.out.println("ID =>" + key + " Name => " + value);
});
}
}
Copy after login

Output:

Java Iterate Map

Explanation:

As you can see in the above code, we have iterated the map with forEach

2. Map key and value iteration separately with forEach loop Example

Code:

package com.map;
import java.util.HashMap;
import java.util.Map;
public class ForEachKeyValueMapIteration {
public static void main(String[] args) {
// creating a hashmap object
Map<Integer, String> names = new HashMap<>();
// adding key and values to hash map
names.put(1, "Paramesh");
names.put(2, "Amardeep");
names.put(3, "Venkatesh");
names.put(4, "Ramesh");
names.put(5, "Suresh");
names.put(3, "Krishna");
names.put(4, "Rama");
names.put(5, "Rajitha");
// iterating ids with forEach loop
names.forEach((key, value) -> {
System.out.println("ID =>" + key);
});
// iterating names with forEach loop
names.forEach((key, value) -> {
System.out.println("Name => " + value);
});
}
}
Copy after login

Output:

Java Iterate Map

Explanation:

As you can see in the above output, we can also fetch the key and values separately with the forEach loop.

3. Map Iteration with for loop Example

Code:

<strong> </strong>import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class ForMapIteration {
public static void main(String[] args) {
// creating a hashmap object
Map<Integer, String> names = new HashMap<>();
// adding key and values to hash map
names.put(1, "Paramesh");
names.put(2, "Amardeep");
names.put(3, "Venkatesh");
names.put(4, "Ramesh");
names.put(5, "Suresh");
names.put(3, "Krishna");
names.put(4, "Rama");
names.put(5, "Rajitha");
// iterating key and value with for loop
for (Entry<Integer, String> entry : names.entrySet())
System.out.println("ID => " + entry.getKey() + " Name => " + entry.getValue());
}
}
Copy after login

Output:

Java Iterate Map

Explanation:

As you can see in the above code, we have iterated the map with for loop.

4. Map key and value iteration separately with for loop Example

Code:

<strong> </strong>import java.util.HashMap;
import java.util.Map;
public class ForKeyAndValueMapIteration {
public static void main(String[] args) {
// creating a hashmap object
Map<Integer, String> names = new HashMap<>();
// adding key and values to hash map
names.put(1, "Paramesh");
names.put(2, "Amardeep");
names.put(3, "Venkatesh");
names.put(4, "Ramesh");
names.put(5, "Suresh");
names.put(3, "Krishna");
names.put(4, "Rama");
names.put(5, "Rajitha");
//fetching ids
for (Integer id : names.keySet())
System.out.println("ID => " + id);
// fetching names
for (String name : names.values())
System.out.println("Name => " + name);
}
}
Copy after login

Output:

Java Iterate Map

Explanation:

As you can see in the above output, we can also fetch the key and values separately with for loop.

5. Map Iteration with while loop and iterator Example

Code:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class WhileIteratorLoopMap {
public static void main(String[] args) {
// creating a hashmap object
Map<Integer, String> names = new HashMap<>();
// adding key and values to hash map
names.put(1, "Paramesh");
names.put(2, "Amardeep");
names.put(3, "Venkatesh");
names.put(4, "Ramesh");
names.put(5, "Suresh");
names.put(3, "Krishna");
names.put(4, "Rama");
names.put(5, "Rajitha");
//get entry set from map
Set set = names.entrySet();
//get iterator from set
Iterator iterator = set.iterator();
//fetching id and names with while loop
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry) iterator.next();
System.out.println("ID =>"+entry.getKey() + " Name => " + entry.getValue());
}
}
}
Copy after login

Output:

Java Iterate Map

Explanation:

As you can see in the above code, we have iterated the map with an iterator and while loop.

Note: All the cases produce the same output, but the forEach loop is recommended for development because it has less run time.

Conclusion – Java Iterate Map

You can iterate over the map using the for loop, forEach loop, and while loop from the Entry interface. We can also iterate keys and values separately without any errors.

The above is the detailed content of Java Iterate Map. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!