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.
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.
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. 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.
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
Right 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.
- Distinction between HashMap and Hashtable in Java? (reply)
- How do you type a Map on keys and values in Java? (reply)
- Array size vs ArrayList measurement()? (learn right here)
- How do you take away() parts from ArrayList in Java? (reply)
- How HashSet works internally in Java? (reply)
- 10 methods to make use of ArrayList in Java? (see right here)
- Distinction between Set, Listing, and Map in Java? (reply)
- When to make use of ArrayList over LinkedList in Java? (reply)
- Distinction between HashSet and HashMap in Java? (reply)
- Distinction between HashMap and LinkdHashMap in Java? (reply)
- When to make use of HashSet vs TreeSet in Java? (reply)
- Easy methods to type ArrayList in growing order in Java? (reply)
- Finest technique to loop by means of ArrayList in Java? (reply)
- Distinction between ConcurrentHashMap vs HashMap in Java? (reply)