Thursday, December 12, 2019

3 Examples To Loop Map Inwards Coffee - Foreach Vs Iterator

There are multiple ways to loop through Map inwards Java, you lot tin either utilization a foreach loop or Iterator to traverse Map inwards Java, but e'er utilization either Set of keys or values for iteration. Since Map yesteryear default doesn't guarantee whatever order, whatever code which assumes a item guild during iteration volition fail. You solely desire to traverse or loop through a Map, if you lot desire to transform each mapping 1 yesteryear one. Now Java 8 unloose provides a novel means to loop through Map inwards Java using Stream API too forEach method. For now, nosotros volition run into 3 ways to loop through each chemical constituent of Map. Though Map is an interface inwards Java, nosotros oft loop through mutual Map implementation like HashMap, Hashtable, TreeMap and LinkedHashMap. By the way, all the ways of traversing Map discussed inwards this article is pretty full general too valid for whatever Map implementation, including proprietary too third-party Map classes.

What I hateful yesteryear looping through Map is getting mappings 1 at a time, processing them too moving forward. Let's say, nosotros accept a Map of Workers, afterward appraisal every worker has got 8% hike, straightaway our project is to update this Map, thus each worker object reflects its new, increased salary.

In guild to exercise this task, nosotros demand to iterate through Map, acquire the Employee object, which is stored equally the value. Update Worker with a novel salary, too deed on. Did you lot enquire close saving it dorsum to Map? no need.

When you lot retrieve values from Map using get() method, they are non removed from Map, thus 1 reference of the same object is e'er in that place inwards Map until you lot take it. That's why, you lot but demand to update object, no demand to relieve it back.

By the way, recollect to override equals() too hashCode() method for whatever object, which you lot are using equally cardinal or value inwards Map. The internal code of  HashMap uses both of these methods to insert too retrieve objects into Map, to acquire to a greater extent than run into How Map plant inwards Java. Now, Let's run into how tin nosotros loop through Map inwards Java.




1) Using for-each loop alongside Entry Set

The Map provides you lot a method called entrySet(), which returns a Set of all Map.Entry objects, which are nix but mapping stored inwards Map. If you lot demand both cardinal too value to process, too then this is the best way, equally you lot acquire both cardinal too value wrapped inwards entry, you lot don't demand to call get() method which goes dorsum to Map in 1 trial to a greater extent than to retrieve the value. Now, enhanced for loop of Java 5 makes your project easy, all you lot demand to exercise is to iterate through that collection equally shown inwards below instance :
        Set<Map.Entry<Integer, Worker>> entrySet = workersById.entrySet();         for (Map.Entry<Integer, Worker> entry : entrySet) {             Worker worker = entry.getValue();             System.out.printf("%s :\t %d %n", worker.getName(),                     worker.getSalary());         }

2) Using Iterator alongside KeySet

If you lot don't require values too solely needs cardinal too then you lot tin utilization Map.keySet() method to acquire a ready of all keys. Now you lot tin utilization Iterator to loop through this Set. If you lot demand value whatever time, too then you lot demand to get(key) method of Map, which returns value from Map. This is an additional trip to map, that's why the previous method is amend if you lot demand both. Here is how to loop through Map using iterator too cardinal ready inwards Java :
        Iterator<Integer> itr = workersById.keySet().iterator();         while (itr.hasNext()) {             Worker electrical current = workersById.get(itr.next());             int increasedSalary = (int) (current.getSalary() * 1.08);             current.setSalary(increasedSalary);         }


3) Using enhanced foreach loop alongside values

Now this is the optimal means of looping through Map if you lot solely demand values, equally it requires less retentiveness than the get-go approach. Here likewise nosotros volition utilization enhanced foreach loop to traverse through values, which is a Collection. We can't utilization evidently onetime for loop alongside index because Collection doesn't render whatever get(index) method, which is solely available inwards List, too it's totally unnecessary to convert Collection to List for iteration only. Here is how to loop Map inwards Java using enhanced for loop too values method :
Collection<Worker> workers = workersById.values();         System.out.println("New Salaries of Workers : ");         for (Worker worker : workers) {             System.out.printf("%s :\t %d %n", worker.getName(),                     worker.getSalary());         }


Complete Java Program to Loop through Map

 There are multiple ways to loop through Map inwards Java 3 Examples to Loop Map inwards Java - Foreach vs IteratorHere is total Java code, which you lot tin run inwards your Java IDE or yesteryear using the ascendancy prompt. Just re-create this code too glue inwards a Java rootage file alongside refer MapLoopDemo and relieve it equally .java extension, compile it using "javac" too run it using "java" command.

import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set;  /**  * Java Program to loop through Map inwards Java. This examples shows iii ways of  * traversing through Map, foreach loop, Iterator alongside ready of keys, entries too  * values from Map.  *  * @author Javin Paul  */ public class HelloJUnit {      private static final Map<Integer, Worker> workersById = new HashMap<>();      public static void main(String args[]) {          // let's initialize Map for useworkersById.put(76832, novel Worker(76832, "Tan", 8000));         workersById.put(76833, new Worker(76833, "Tim", 3000));         workersById.put(76834, new Worker(76834, "Tarun", 5000));         workersById.put(76835, new Worker(76835, "Nikolai", 6000));         workersById.put(76836, new Worker(76836, "Roger", 3500));          // looping through map using foreach loop         // impress initial salary of workers         System.out.println("Initial Salaries of workers");          Set<Map.Entry<Integer, Worker>> entrySet = workersById.entrySet();          for (Map.Entry<Integer, Worker> entry : entrySet) {             Worker worker = entry.getValue();             System.out.printf("%s :\t %d %n", worker.getName(),                     worker.getSalary());         }          // looping through map using Iterator         // updating salary of each worker         Iterator<Integer> itr = workersById.keySet().iterator();         while (itr.hasNext()) {             Worker electrical current = workersById.get(itr.next());             int increasedSalary = (int) (current.getSalary() * 1.08);             current.setSalary(increasedSalary);         }          // how to loop map using for loop         // looping through values using for loop         Collection<Worker> workers = workersById.values();         System.out.println("New Salaries of Workers : ");         for (Worker worker : workers) {             System.out.printf("%s :\t %d %n", worker.getName(),                     worker.getSalary());         }      }      private static class Worker {          private int id;         private String name;         private int salary;          public Worker(int id, String name, int salary) {             this.id = id;             this.name = name;             this.salary = salary;         }          public final int getId() {             return id;         }          public final String getName() {             return name;         }          public final int getSalary() {             return salary;         }          public final void setId(int id) {             this.id = id;         }          public final void setName(String name) {             this.name = name;         }          public final void setSalary(int salary) {             this.salary = salary;         }          @Override         public String toString() {             return "Worker [id=" + id + ", name=" + refer + ", salary=" + salary                     + "]";         }          @Override         public int hashCode() {             final int prime number = 31;             int number = 1;             number = prime number * number + id;             number = prime number * number + ((name == null) ? 0 : name.hashCode());             number = prime number * number + (int) (salary ^ (salary >>> 32));             return result;         }          @Override         public boolean equals(Object obj) {             if (this == obj) {                 return true;             }             if (obj == null) {                 return false;             }             if (getClass() != obj.getClass()) {                 return false;             }             Worker other = (Worker) obj;             if (id != other.id) {                 return false;             }             if (name == null) {                 if (other.name != null) {                     return false;                 }             } else if (!name.equals(other.name)) {                 return false;             }             if (salary != other.salary) {                 return false;             }             return true;         }     } }  Output: Initial Salaries of workers Tim :    3000 Tan :    8000 Nikolai :        6000 Tarun :  5000 Roger :  3500 New Salaries of Workers : Tim :    3240 Tan :    8640 Nikolai :        6480 Tarun :  5400 Roger :  3780

That's all close how to loop through Map inwards Java. Traversing is a mutual project inwards whatever programming linguistic communication too many of them provides easier syntax, reverse to that, In Java you lot demand to write a lot of boilerplate code too our functional intent is hidden betwixt boilerplate code. Java 8 is coming upward alongside to a greater extent than expressive means to exercise mutual project inwards collection using lambda expressions and volume information operations. For examples project similar looping through List, filtering sure enough elements, transforming 1 object to roughly other too reducing them into 1 value volition move real easy. So far, you lot tin utilization inwards a higher house examples to loop through your Map inwards Java. All examples are valid for whatever Map implementations including HashMap, Hashtable, TreeMap and LinkedHashMap.

Further Learning
Java In-Depth: Become a Complete Java Engineer
answer)
  • How exercise you lot kind a Map on keys too values inwards Java? (answer)
  • Array length vs ArrayList size()?  (read here)
  • How exercise you lot remove() elements from ArrayList inwards Java? (answer)
  • How HashSet plant internally inwards Java? (answer)
  • 10 ways to utilization ArrayList inwards Java? (see here)
  • Difference betwixt Set, List and Map in Java? (answer)
  • When to utilization ArrayList over LinkedList in Java? (answer)
  • Difference betwixt HashSet and HashMap inwards Java? (answer)
  • Difference betwixt HashMap and LinkdHashMap in Java? (answer)
  • When to utilization HashSet vs TreeSet in Java? (answer)
  • How to kind ArrayList inwards increasing guild inwards Java? (answer)
  • Best means to loop through ArrayList in Java? (answer)
  • Difference betwixt ConcurrentHashMap vs HashMap in Java? (answer)
  • No comments:

    Post a Comment