Monday, June 23, 2025
HomeJava3 Examples to Loop Map in Java - Foreach vs Iterator

3 Examples to Loop Map in Java – Foreach vs Iterator


There are a number of methods to loop by means of Map in Java, you’ll be able to both use a foreach loop or Iterator to traverse Map in Java, however all the time use both Set of keys or values for iteration. Since Map by default does not assure any order, any code which assumes a specific order throughout iteration will fail. You solely need to traverse or loop by means of a Map, if you wish to remodel every mapping one after the other. Now Java 8 launch offers a brand new technique to loop by means of Map in Java utilizing Stream API and forEach technique. For now, we are going to see 3 methods to loop by means of every aspect of Map
Although Map is an interface in Java, we frequently loop by means of frequent Map implementation like HashMap, Hashtable, TreeMap, and LinkedHashMap. By the way in which, all of the methods of traversing Map mentioned on this article is fairly normal and legitimate for any Map implementation, together with proprietary and third-party Map courses.

What I imply by looping by means of Map is getting mappings separately, processing them, and shifting ahead. To illustrate, we have now a Map of Staff, after appraisal, each employee has obtained an 8% hike, now our job is to replace this Map, so every employee’s object displays its new, elevated wage.

To be able to do that job, we have to iterate by means of Map, get the Worker object, which is saved as the worth. Replace Employee with a brand new wage, and transfer on. Did you ask about saving it again to Map? no want.

Whenever you retrieve values from Map utilizing the get() technique, they don’t seem to be faraway from Map, so one reference of the identical object is all the time there in Map till you take away it. That is why, you simply must replace an object, no want to reserve it again.

By the way in which, keep in mind to override equals() and hashCode() technique for any object, which you might be utilizing as key or worth in Map. The inner code of  HashMap makes use of each of those strategies to insert and retrieve objects into Map, to study extra see How Map works in Java. Now, Let’s have a look at how can we loop by means of Map in Java.

1. Utilizing for-each loop with Entry Set 

The Map offers you a way referred to as entrySet(), which returns a Set of all Map.Entry objects, that are nothing however mapping saved in Map. In case you want each key and worth to the method, then that is one of the simplest ways, as you get each key and worth wrapped in entry, you needn’t name the get() technique which works again to Map once more to retrieve the worth. 

Now, enhanced for loop of Java 5 makes your job simple, all it’s essential to do is to iterate by means of that assortment as proven within the under instance :

        Set<Map.Entry<Integer, Employee>> entrySet = workersById.entrySet();
        for (Map.Entry<Integer, Employee> entry : entrySet) {
            Employee employee = entry.getValue();
            System.out.printf("%s :t %d %n", employee.getName(),
                    employee.getSalary());
        }

2. Utilizing Iterator with KeySet

In case you do not require values and solely want a key then you should utilize Map.keySet() technique to get a set of all keys. Now you should utilize Iterator to loop by means of this Set. In case you want worth any time, then it’s essential to get(key) technique of Map, which returns a price from Map. 

That is an extra journey to map, that is why the earlier technique is best for those who want each. Right here is how you can loop by means of Map utilizing iterator and key set in Java :

        Iterator<Integer> itr = workersById.keySet().iterator();
        whereas (itr.hasNext()) {
            Employee present = workersById.get(itr.subsequent());
            int increasedSalary = (int) (present.getSalary() * 1.08);
            present.setSalary(increasedSalary);
        }
3 Examples to Loop Map in Java - Foreach vs Iterator

3. Utilizing enhanced foreach loop with values

Now, that is the optimum approach of looping by means of Map for those who solely want values, because it requires much less reminiscence than the primary method. Right here additionally we are going to use an enhanced foreach loop to traverse by means of values, which is a Assortment

We won’t use plain outdated for loop with index as a result of Assortment does not present any get(index) technique, which is just out there in Listing, and it’s very pointless to convert Assortment to Listing for iteration solely. Right here is how you can loop Map in Java utilizing enhanced for loop and values technique :

Assortment<Employee> employees = workersById.values();
        System.out.println("New Salaries of Staff : ");
        for (Employee employee : employees) {
            System.out.printf("%s :t %d %n", employee.getName(),
                    employee.getSalary());
        }

Full Java Program to Loop by means of Map

How to loop a Map in Java with ExampleRight here is full Java code, which you’ll be able to run in your Java IDE or through the use of the command immediate. Simply copy this code and paste right into a Java supply file with the title MapLoopDemo and put it aside as .java extension, compile it utilizing “javac” and run it utilizing “java” command.

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

/**
 * Java Program to loop by means of Map in Java. This examples reveals 3 ways of
 * traversing by means of Map, foreach loop, Iterator with set of keys, entries and
 * values from Map.
 *
 * @writer Javin Paul
 */
public class HelloJUnit {

    personal static last Map<Integer, Employee> workersById = new HashMap<>();

    public static void predominant(String args[]) {

        // let's initialize Map for 
        // useworkersById.put(76832, new Employee(76832, "Tan", 8000));
        workersById.put(76833, new Employee(76833, "Tim", 3000));
        workersById.put(76834, new Employee(76834, "Tarun", 5000));
        workersById.put(76835, new Employee(76835, "Nikolai", 6000));
        workersById.put(76836, new Employee(76836, "Roger", 3500));

        // looping by means of map utilizing foreach loop
        // print preliminary wage of employees
        System.out.println("Preliminary Salaries of employees");

        Set<Map.Entry<Integer, Employee>> entrySet = workersById.entrySet();

        for (Map.Entry<Integer, Employee> entry : entrySet) {
            Employee employee = entry.getValue();
            System.out.printf("%s :t %d %n", employee.getName(),
                    employee.getSalary());
        }

        // looping by means of map utilizing Iterator
        // updating wage of every employee
        Iterator<Integer> itr = workersById.keySet().iterator();
        whereas (itr.hasNext()) {
            Employee present = workersById.get(itr.subsequent());
            int increasedSalary = (int) (present.getSalary() * 1.08);
            present.setSalary(increasedSalary);
        }

        // how you can loop map utilizing for loop
        // looping by means of values utilizing for loop
        Assortment<Employee> employees = workersById.values();
        System.out.println("New Salaries of Staff : ");
        for (Employee employee : employees) {
            System.out.printf("%s :t %d %n", employee.getName(),
                    employee.getSalary());
        }

    }

    personal static class Employee {

        personal int id;
        personal String title;
        personal int wage;

        public Employee(int id, String title, int wage) {
            this.id = id;
            this.title = title;
            this.wage = wage;
        }

        public last int getId() {
            return id;
        }

        public last String getName() {
            return title;
        }

        public last int getSalary() {
            return wage;
        }

        public last void setId(int id) {
            this.id = id;
        }

        public last void setName(String title) {
            this.title = title;
        }

        public last void setSalary(int wage) {
            this.wage = wage;
        }

        @Override
        public String toString() {
            return "Employee [id=" + id + ", name=" + name + ", salary=" + salary
                    + "]";
        }

        @Override
        public int hashCode() {
            last int prime = 31;
            int end result = 1;
            end result = prime * end result + id;
            end result = prime * end result + ((title == null) ? 0 : title.hashCode());
            end result = prime * end result + (int) (wage ^ (wage >>> 32));
            return end result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            Employee different = (Employee) obj;
            if (id != different.id) {
                return false;
            }
            if (title == null) {
                if (different.title != null) {
                    return false;
                }
            } else if (!title.equals(different.title)) {
                return false;
            }
            if (wage != different.wage) {
                return false;
            }
            return true;
        }
    }
}

Output:
Preliminary Salaries of employees
Tim :    3000
Tan :    8000
Nikolai :        6000
Tarun :  5000
Roger :  3500
New Salaries of Staff :
Tim :    3240
Tan :    8640
Nikolai :        6480
Tarun :  5400
Roger :  3780

That is all about how you can loop by means of Map in Java. Traversing is a standard job in any programming language and plenty of of them present simpler syntax, opposite to that, In Java, it’s essential to write lots of boilerplate code and our practical intent is hidden between boilerplate code. Java 8 is developing with a extra expressive technique to do the frequent duties within the assortment utilizing lambda expressions and bulk information operations. 

For examples job like looping by means of a Listing, filtering sure parts, remodeling one object to a different, and lowering them into one worth can be very simple. To this point, you should utilize the above examples to loop by means of your Map in Java. All examples are legitimate for any Map implementations together with HashMap, Hashtable, TreeMap, and LinkedHashMap.

Wish to study extra in regards to the Java Assortment framework? try these wonderful articles

  1. Distinction between HashMap and Hashtable in Java? (reply)
  2. How do you type a Map on keys and values in Java? (reply)
  3. Array size vs ArrayList measurement()?  (learn right here)
  4. How do you take away() parts from ArrayList in Java? (reply)
  5. How HashSet works internally in Java? (reply)
  6. 10 methods to make use of ArrayList in Java? (see right here)
  7. Distinction between Set, Listing, and Map in Java? (reply)
  8. When to make use of ArrayList over LinkedList in Java? (reply)
  9. Distinction between HashSet and HashMap in Java? (reply)
  10. Distinction between HashMap and LinkdHashMap in Java? (reply)
  11. When to make use of HashSet vs TreeSet in Java? (reply)
  12. Easy methods to type ArrayList in growing order in Java? (reply)
  13. Finest technique to loop by means of ArrayList in Java? (reply)
  14. Distinction between ConcurrentHashMap vs HashMap in Java? (reply)
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments