Showing posts with label HashMap. Show all posts
Showing posts with label HashMap. Show all posts

Saturday, March 28, 2020

10 Examples Of Hashmap Inwards Coffee - Programming Tutorial

The HashMap inward Java is i of the most pop Collection course of didactics alongside Java programmers. After my article on How HashMap plant inward Java, which describes theory component subdivision of Java HashMap as well as becomes hugely pop alongside Java programmers, I idea to portion how to utilization HashMap inward Java with around key HashMap examples, but couldn't practice that before as well as it was slipped. The HashMap is a information structure, based on hashing, which allows you lot to shop an object every bit a key-value pair, an payoff of using HashMap is that you lot tin recollect object on constant fourth dimension i.e. O(1) if you lot know the key.

The HashMap course of didactics implements Map interface as well as supports Generics from Java 1.5 release, which makes it type safe. There are a brace of to a greater extent than Collections, which provides similar functionalities similar HashMap, which tin besides endure used to shop key value pair.

Hashtable is i of them, but Hashtable is synchronized as well as performs poorly inward a unmarried threaded environment. See Hashtable vs HashMap for consummate differences betwixt them.

Another one, relatively novel is ConcurrentHashMap, which provides amend performance than Hashtable inward a concurrent surroundings as well as should endure preferred. See the difference betwixt ConcurrentHashMap as well as HashMap for exceptional differences.

In this Java tutorial, nosotros volition come across dissimilar examples of HashMap, similar adding as well as removing entries, iterating over Java HashMap, checking size map, finding if a key or value exists on Map as well as diverse other examples, which nosotros used frequently.



Java HashMap Example

Before going to come across these examples, few things to banknote almost Java HashMap.It’s non synchronized, hence don't portion your HashMap alongside multiple threads. 

Another mutual crusade of the mistake is clearing Map as well as reusing it, which is perfectly valid inward a unmarried threaded surroundings but if done inward a multi-threaded surroundings tin create subtle bugs.

Java HashMap Example 1: Create as well as add together objects inward HashMap

In the outset representative of HashMap, nosotros volition create as well as add together an object to our Map. Always utilization Generics, if you lot are non working inward Java 1.4. The next code volition create HashMap with keys of type String as well as values of type Integer with default size as well as charge factor.

HashMap<String, Integer> cache = novel HashMap<String, Integer>();

alternatively, you lot tin create HashMap from copying information from around other Map or Hashtable every bit shown inward below example:
 
Hashtable<Integer, String> root = novel Hashtable<Integer,String>(); HashMap<Integer, String>  map = novel HashMap(source);

You tin besides render charge gene (percentage of size, which if filled trigger resizes of HashMap) as well as initial capacity spell creating an instance past times using overloaded constructor provided inward API.

Adding elements besides called the lay functioning inward HashMap as well as requires a key as well as a value object.

Here is an representative of adding key as well as value inward Java HashMap:

map.put(21, "Twenty One"); map.put(21.0, "Twenty One"); //this volition throw compiler error because 21.0 is not integer

You tin farther see how does get() method internally piece of job inward Java to larn to a greater extent than almost retrieving mapping inward Java. The article explains how get() method uses equals() as well as hashCode() to recollect value object fifty-fifty inward representative of collision.

4 ways to loop HashMap inward Java.

Here is an representative of iterating over Map using java.util.Iterator :

map.put(21, "Twenty One"); map.put(31, "Thirty One");         Iterator<Integer> keySetIterator = map.keySet().iterator();  while(keySetIterator.hasNext()){   Integer key = keySetIterator.next();   System.out.println("key: " + key + " value: " + map.get(key)); }  Output: key: 21 value: Twenty One key: 31 value: Thirty One

You tin besides refer forEach() method inward Java 8.

 inward Java is i of the most pop Collection course of didactics alongside Java programmers 10 Examples of HashMap inward Java - Programming Tutorial


Java HashMap Example 4: Size as well as Clear inward HashMap

Two key examples of HashMap is finding out how many elements are stored inward Map, known every bit the size of Map as well as clearing HashMap to reuse. Java Collection API provides ii convenient methods called size() as well as clear() to perform these operations on java.util.HashMap, hither is code example.

System.out.println("Size of Map: " + map.size()); map.clear(); //clears hashmap , removes all element System.out.println("Size of Map: " + map.size());   Output: Size of Map: 2 Size of Map: 0


You tin reuse Map past times clearing it, but endure careful if it's been shared betwixt multiple threads without proper synchronization. Since you lot may need to preclude other thread from accessing map when it's getting clear. I propose non to practice until you lot receive got a really proficient argue for doing it.


Java HashMap Example five as well as 6: ContainsKey as well as ContainsValue Example

In this representative of Java HashMap, nosotros volition larn how to cheque if Map contains a exceptional object every bit key or value. java.util.HashMap provides convenient methods similar containsKey(Object key) as well as containsValue(Object value) which tin endure used to for checking the beingness of whatever key value inward HashMap.

Here is a code representative :

System.out.println("Does HashMap contains 21 every bit key: " + map.containsKey(21)); System.out.println("Does HashMap contains 21 every bit value: " + map.containsValue(21)); System.out.println("Does HashMap contains Twenty One every bit value: " + map.containsValue("Twenty One"));   Output: Does HashMap contains 21 every bit key: true Does HashMap contains 21 every bit value: false  Does HashMap contains Twenty One every bit value: true



Java HashMap Example 7: Checking if HashMap is empty

In this Map example, nosotros volition larn how to cheque if HashMap is empty inward Java. There are ii ways to honour out if Map is empty, i is using size() method if size is null agency Map is empty.

Another way to cheque if HashMap is empty is using to a greater extent than readable isEmpty() method which returns truthful if Map is empty.

Here is code representative :

boolean isEmpty = map.isEmpty(); System.out.println("Is HashMap is empty: " + isEmpty);  Output: Is HashMap is empty: false



Java HashMap Example 8: Removing Objects from HashMap

Another mutual representative of Java HashMap is removing entries or mapping from Map. The java.util.HashMap provides remove(Object key) method, which accepts key as well as removes mapping for that key.

This method returns zip or the value of the entry, merely removed. You tin besides see how to form HashMap on keys as well as values for a total code example.

Alternatively, you lot tin utilization SortedMap inward Java similar TreeMap. TreeMap has a constructor which accepts Map as well as tin create a Map sorted on the natural guild of key or whatever custom sorting guild defined past times Comparator.

Only affair is key should endure naturally comparable as well as their compareTo() method shouldn't throw an exception. Just to remind at that spot are no Collections.sort() method defined for Map is exclusively for List as well as it’s implementation e.g. ArrayList or LinkedList.

So whatever sorting for Map requires SortedMap or custom code for sorting on either key or value. hither is code representative of sorting HashMap inward Java past times using TreeMap inward the natural guild of keys:

map.put(21, "Twenty One"); map.put(31, "Thirty One"); map.put(41, "Thirty One");  System.out.println("Unsorted HashMap: " + map); TreeMap sortedHashMap = new TreeMap(map);      System.out.println("Sorted HashMap: " + sortedHashMap);   Output: Unsorted HashMap: {21=Twenty One, 41=Thirty One, 31=Thirty One} Sorted HashMap: {21=Twenty One, 31=Thirty One, 41=Thirty One}



Java HashMap Example 10: Synchronized HashMap inward Java

You need to synchronize HashMap if you lot desire to utilization it inward a multi-threaded environment. If you lot are running on Java 1.5 as well as higher upwards consider using ConcurrentHashMap inward house of synchronized HashMap because it provides amend concurrency.

If your projection is nevertheless on JDK 1.4 hence you lot got to utilization either Hashtable or synchronized Map.

The Collections.synchronizedMap(map) is used to synchronize HashMap inward Java. See here for a total code example. This method returns a thread-safe version of Map as well as all map functioning is serialized.


Further Learning
Java In-Depth: Become a Complete Java Engineer
Difference betwixt HashMap as well as ArrayList inward Java
When to utilization Map, List, as well as Set collection inward Java
Difference betwixt HashMap as well as HashSet inward Java
Difference betwixt IdentityHashMap as well as HashMap inward Java

Friday, March 27, 2020

How Exceed Method Of Hashmap Or Hashtable Industrial Plant Internally Inwards Java

In this article, I am revisiting a duo of interesting query related to the internal working of HashMap inward Java, by together with large asked senior Java developers, ranging from four to half dozen together with upwards to 8 years of experience. I did encompass lot of these questions from HashMap, ranging from thread-safety to race conditions, inward my postal service near internal working of Java HashMap, but I idea to revisit 2 of those questions, How acquire method of HashMap or Hashtable plant internally in Java together with What happens if 2 dissimilar keys provide the same hashCode, how create y'all provide value from HashMap inward that case. These are the question, which is highly pop inward investment banking domain, together with preferred selection of interviewer, piece interviewing experienced Java professional. 

If these questions are however beingness asked, it agency non many are answering them inward the clarity together with confidence they are looking for. This motivates me to revisit these questions again. On a side note, inward fellowship to sympathize these questions, y'all should accept practiced cognition of equals together with hashcode method every bit well. 

At to the lowest degree y'all should know that :
1) Two unequal objects may provide the same hashcode.
2) When 2 objects are equal past times equals(), they must accept the same hashcode.




How acquire method of Hashtable plant inward Java

HashMap, Hashtable, together with ConcurrentHashMap

Another optional, but worth mentioning requirement of keys inward a hash-based collection is beingness an Immutable object. Keeping this cognition along amongst full general cognition of hashing algorithm, which revolves simply about hash function. 

You should read a proper majority on information construction together with algorithms to larn to a greater extent than near how a hash business office plant together with dissimilar strategies to handgrip collisions inward Java. One of such majority is Introduction to Algorithms past times Thomas Cormen, perfect for whatsoever programmer interested inward learning to a greater extent than near algorithms together with information structures. 


 I am revisiting a duo of interesting query related to the internal working of HashM How acquire method of HashMap or Hashtable plant internally inward Java


Anyway, let's run across those HashMap questions in i lawsuit again :

1) How does get(Key key) method plant internally inward HashMap, together with Hashtable inward Java?
Here are steps, which happens, when y'all telephone holler upwards get() method amongst fundamental object to call upwards corresponding value from hash based collection

a) Key.hashCode() method is used to notice the bucket place inward backing array. (Remember HashMap is backed past times array inward Java) Though hashcode() is non used directly, but they are passed to internal hash() function.

b) In backing array or meliorate known every bit the bucket, fundamental together with values are stored inward the shape of a nested shape called Entry.  If at that spot is solely i Entry at bucket location, thus the value from that entry is returned. Pretty straightforward right?

Things acquire fiddling tricky, when Interviewer inquire the instant question, What happens if 2 keys accept the same hashCode? If multiple keys accept the same hashCode, thus during put() performance collision had occurred, which agency multiple Entry objects stored inward a bucket location. Each Entry keeps rail of some other Entry, forming a linked listing information structure there.  

how HashMap together with LinkedHashMap handgrip collision inward Java to larn to a greater extent than near this change. 

Now, if nosotros demand to call upwards value object inward this situation, next steps volition last followed :

1) Call hashCode() method of the fundamental to finding bucket location.

2) Traverse idea linked list, comparison keys inward each entries using keys.equals() until it returns true.

So, nosotros utilization equals() method of a fundamental object to notice right entry together with thus provide value from that. Remember key.equals() method, together with this is what Interviewer desire to know. I accept seen many programmers mentioning value.equals(), which may last due to interview nervousness, but that’s incorrect. Since y'all don't accept value object passed to get() method, at that spot is no query of calling equals together with hashCode method on value object.

That's all on these 2 HashMap questions guys. Remember to call near key.hashCode() together with key.equals(), whenever mortal asks how to acquire method of HashMap or Hashtable plant inward Java. H5N1 value object is non used, it simply exists inward Entry thus that acquire tin provide it.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Difference betwixt ConcurrentHashMap together with HashMap inward Java

Thursday, December 12, 2019

How Hashset Internally Industrial Plant Inwards Java

Not many programmer know that HashSet is internally implemented using HashMap in Java, hence if you lot know How HashMap industrial plant internally inwards Java, to a greater extent than probable you lot tin figure out how HashSet industrial plant inwards Java. But, at nowadays a curious Java developer tin enquiry that, how come upward HashSet uses HashMap, because you lot request a key value twain to usage amongst Map, spell inwards HashSet we alone shop ane object. Good question, isn't it? If you lot recall to a greater extent than or less functionality of before class, in addition to hence you lot know that HashMap allows duplicate values in addition to this belongings is exploited spell implementing HashSet inwards Java. Since HashSet implements Set interface it needs to guarantee uniqueness in addition to this is achieved past times storing elements every bit keys amongst same value always. Things gets clear past times checking HashSet.java from JDK root code. All you lot request to await at is, how elements are stored inwards HashSet in addition to how they are retrieved from HashSet. Since HashSet doesn't supply whatever right away method for retrieving object e.g. get(Key key) from HashMap or get(int index) from List, alone agency to acquire object from HashSet is via Iterator. See here for code representative of iterating over HashSet inwards Java. When you lot exercise an object of HashSet inwards Java, it internally exercise event of backup Map amongst default initial capacity sixteen in addition to default charge cistron 0.75 every bit shown below :

/**
  * Constructs a new, empty set; the backing <tt>HashMap</tt> event has   * default initial capacity (16) in addition to charge cistron (0.75).   */  populace HashSet() {    map = new HashMap<>(); }

Now let's run into the code for add() in addition to iterate() method from java.util.HashSet inwards Java to sympathise how HashSet industrial plant internally inwards Java.



How Object is stored inwards HashSet
As you lot tin run into below, a telephone outcry upward to add(Object) is delegate to put(Key, Value) internally, where Key is the object you lot bring passed in addition to value is to a greater extent than or less other object,  called PRESENT, which is a constant inwards java.util.HashSet every bit shown below :

private transient HashMap<E,Object> map;  // Dummy value to associate amongst an Object inwards the backing Map private static final Object PRESENT = new Object();  populace boolean add(E e) {    return map.put(e, PRESENT)==null; }

Since PRESENT is a constant, for all keys nosotros bring same value inwards backup HashMap called map.


How Object is retrieved from HashSet
Now let's run into the code for getting iterator for traversing over HashSet inwards Java. iterator() method from java.util.HashSet class returns iterator for backup Map returned past times map.keySet().iterator() method.

       /**
     * Returns an iterator over the elements inwards this set.  The elements      * are returned inwards no item order.      *      * @return an Iterator over the elements inwards this set      * @see ConcurrentModificationException      */      populace Iterator<E> iterator() {         return map.keySet().iterator();     }
 
 

How to usage HashSet inwards Java

Using HashSet in Java is rattling simple, don't mean value it is Map but mean value to a greater extent than similar Collection i.e. add together elements past times using add() method, cheque its render value to run into if object already existed inwards HashSet or not. Similarly usage iterator for retrieving chemical cistron from HashSet in Java. You tin too usage contains() method to cheque if whatever object already exists inwards HashSet or not. This method usage equals() method for comparison object for matching. You tin too usage remove() method to take object from HashSet. Since chemical cistron of HashSet is used every bit key inwards backup HashMap, they must implement equals() in addition to hashCode() method. Immutability is non requirement exactly if its immutable in addition to hence you lot tin assume that object volition non live on changed during its rest on set. Following representative demonstrate basic usage of HashSet in Java, for to a greater extent than advanced example, you lot tin cheque this tutorial.    

import java.util.HashSet; import java.util.Iterator;   /**  * Java Program to demonstrate How HashSet industrial plant internally inwards Java.  * @author http://java67.blogspot.com  */  public class HashSetDemo{          public static void main(String args[]) {        HashSet<String> supportedCurrencies = new HashSet<String>();                      // adding object into HashSet, this volition live on translated to put() calls       supportedCurrencies.add("USD");       supportedCurrencies.add("EUR");       supportedCurrencies.add("JPY");       supportedCurrencies.add("GBP");       supportedCurrencies.add("INR");       supportedCurrencies.add("CAD");        // retrieving object from HashSet       Iterator<String> itr = supportedCurrencies.iterator();       while(itr.hasNext()){          System.out.println(itr.next());        }    }  }  Output JPY EUR INR USD CAD GBP

That's all close How HashSet is implemented inwards Java in addition to How HashSet industrial plant internally. As I said, If you lot how HashMap internally inwards Java, you lot tin explicate working of HashSet provided,  you know it uses same values for all keys. Remember to override equals() in addition to hashCode() for whatever object you lot are going to shop inwards HashSet, since your object is used every bit key inwards backup Map, it must override those method. Make your object Immutable or effective immutable if possible.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures in addition to Algorithms: Deep Dive Using Java
Algorithms in addition to Data Structures - Part 1 in addition to ii
Data Structures inwards Java ix past times Heinz Kabutz


2 Ways To Course Of Didactics Hashmap Inwards Java? Example

So you lot conduct hold a Map inwards your Java programme together with you lot desire to procedure its information inwards sorted order. Since Map doesn't guarantee whatever guild for its keys together with values, you lot ever halt upwards amongst unsorted keys together with Map. If you lot actually bespeak a sorted Map together with then recollect virtually using TreeMap, which keeps all keys inwards a sorted order. This could travel either natural guild of keys (defined past times Comparable) or a custom guild (defined past times Comparator), which you lot tin render piece creating an event of TreeMap. If you lot don't conduct hold your information inwards a sorted Map together with then solely selection remains is to acquire the keys, variety them together with and then procedure information inwards that order. Since keys are unique inwards Map, it returns a Set of keys, which way you lot cannot variety them past times using Collections.sort() method, which bring a List. So what to do? Well, nosotros tin convert our Set into List equally shown inwards this example, together with then variety them using sort() method inwards whatever guild together with procedure them accordingly.

Now which approach is better, either using TreeMap or keeping mappings inwards an unsorted full general role Map implementation similar HashMap or Hashtable? good both conduct hold their advantages together with disadvantages, but if requirement is ever proceed keys inwards sorted guild together with then usage TreeMap, though insertions volition travel dull but keys volition ever rest inwards sorted order.

On the other hand, if requirement is but to procedure information inwards a item order, which too varies depending upon which method is using Map, together with then usage full general role Map e.g. HashMap and solely variety when needed. Insertion volition travel much faster, but it volition require additional fourth dimension to variety keys earlier processing. In adjacent section, nosotros volition meet representative of both approach of sorting Map inwards Java.




2 ways to variety HashMap inwards Java

 So you lot conduct hold a Map inwards your Java programme together with you lot desire to procedure its information inwards sorted guild 2 Ways to variety HashMap inwards Java? Examplethis article.

import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap;  /**  *  * Java Program of sorting Map past times keys inwards Java.   * You tin usage this technique to variety HashMap,   * Hashtable, ConcurrentHashMap, LinkedHashMap or   * whatever arbitrary implementation of Map interface inwards Java.  *  * @author Javin Paul  */ public class MapSorterDemo{      public static void main(String args[]) {         // Unsorted Integer to String Map         Map<Integer, String> idToName = new HashMap<>();         idToName.put(1001, "Joe");         idToName.put(1003, "Kevin");         idToName.put(1002, "Peter");         idToName.put(1005, "Johnson");         idToName.put(1004, "Ian");          System.out.println("unsorted map : " + idToName);          // Sorting Map past times keys         TreeMap<Integer, String> sorted = new TreeMap<>(idToName);         System.out.println("sorted map : " + sorted);          // If you lot desire to procedure Map inwards sorted guild of keys         // together with then you lot tin proceed an unsorted Map, but bring the         // keyset together with variety them, earlier processing         Set<Integer> ids = idToName.keySet();         System.out.println("unsorted keys of map : " + ids);                 List<Integer> sortedIds = new ArrayList<>(ids);         Collections.sort(sortedIds);         System.out.println("sorted keys of map : " + sortedIds);     }  }  Output: unsorted map : {1001=Joe, 1003=Kevin, 1002=Peter, 1005=Johnson, 1004=Ian} sorted map : {1001=Joe, 1002=Peter, 1003=Kevin, 1004=Ian, 1005=Johnson} unsorted keys of map : [1001, 1003, 1002, 1005, 1004] sorted keys of map : [1001, 1002, 1003, 1004, 1005]

That's all virtually how to variety Map inwards Java. We conduct hold learned two ways to variety Map past times keys, kickoff past times using TreeMap, which requires to re-create content of master copy map together with exercise a sorted map, second, past times solely sorting keys. Both approach has their pros together with cons together with you lot should usage TreeMap, if sorting together with ordering of key is a requirement. If your concern logic require you lot to procedure mapping inwards unlike guild at unlike time, together with then you lot tin nonetheless proceed information inwards full general role Map implementation e.g. HashMap together with solely variety them when needed using Collections.sort() method.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures together with Algorithms: Deep Dive Using Java
Algorithms together with Data Structures - Part 1 together with 2
Data Structures inwards Java ix past times Heinz Kabutz

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)
  • Wednesday, December 11, 2019

    How To Course Of Didactics Hashmap Inward Coffee Based On Keys Together With Values

    HashMap is non meant to proceed entries inwards sorted order, but if you lot guide hold to form HashMap based upon keys or values, you lot tin practice that inwards Java. Sorting HashMap on keys is quite easy, all you lot demand to practice is to practice a TreeMap past times copying entries from HashMap. TreeMap is an implementation of SortedMap as well as keeps keys inwards their natural club or a custom club specified past times Comparator provided piece creating TreeMap. This way you lot tin procedure entries of HashMap inwards a sorted club but you lot cannot top a HashMap containing mappings inwards a specific order, this is simply non possible because HashMap doesn't guarantee whatsoever ordering. On other hand, sorting HashMap past times values is rather complex because at that spot is no straight method to back upward that operation. You demand to write code for that. In club to form HashMap past times values you lot tin starting fourth dimension practice a Comparator, which tin compare 2 entries based on values. Then acquire the Set of entries from Map, convert Set to List as well as usage Collections.sort(List) method to form your listing of entries past times values past times passing your customized value comparator. This is like of how you lot form an ArrayList inwards Java. Half of the undertaking is done past times now. Now practice a novel LinkedHashMap as well as add together sorted entries into that. Since LinkedHashMap guarantees insertion club of mappings, you lot volition survive guide hold a Map where contents are sorted past times values.



    Steps to form HashMap past times values

    One deviation betwixt sorting HashMap past times keys as well as values is that it tin incorporate duplicate values past times non duplicate keys. You cannot usage TreeMap hither because it exclusively form entries past times keys. In this illustration you lot demand to :
    1. Get all entries past times calling entrySet() method of Map
    2. Create a custom Comparator to form entries based upon values
    3. Convert entry laid upward to list
    4. Sort entry listing past times using Collections.sort() method past times passing your value comparator
    5. Create a LinkedHashMap past times adding entries inwards sorted order.




    Steps to form HashMap past times keys

    There are 2 ways to sort HashMap past times keys, starting fourth dimension past times using TreeMap as well as minute past times using LinkedHashMap. If you lot desire to form using TreeMap as well as hence it's simple, simply practice a TreeMap past times copying content of HashMap. On the other hand, if you lot desire to practice a LinkedHashMap as well as hence you lot starting fourth dimension demand to acquire key set, convert that Set to List, form that List as well as and hence add together them into LHM inwards same order. Remember HashMap tin incorporate i null key but duplicate keys are non allowed.



    HashMap Sorting past times Keys as well as Values inwards Java Example

    overrides comapre() method as well as accepts 2 entries. Later it retrieves values from those entries as well as compare them as well as render result. Since at that spot is no method inwards Java Collection API to form Map, nosotros demand to usage Collections.sort() method which accepts a List. This involves creating a temporary ArrayList alongside entries for sorting usage as well as and hence in i lawsuit again copying entries from sorted ArrayList to a novel LinkedHashMap to proceed them inwards sorted order. Finally nosotros practice a HashMap from that LinkedHashMap, which is what nosotros needed.

    import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap;  /**  * How to form HashMap inwards Java past times keys as well as values.   * HashMap doesn't guarantee whatsoever order, hence you lot cannot rely on it, fifty-fifty if  * it seem that it storing entries inwards a detail order, because  * it may non live available inwards hereafter version e.g. before HashMap stores  * integer keys on the club they are inserted but from Java 8 it has changed.  *   * @author WINDOWS 8  */  public class HashMapSorting{      public static void main(String args[]) throws ParseException {                  // let's practice a map alongside Java releases as well as their code names         HashMap<String, String> codenames = new HashMap<String, String>();                  codenames.put("JDK 1.1.4", "Sparkler");         codenames.put("J2SE 1.2", "Playground");         codenames.put("J2SE 1.3", "Kestrel");         codenames.put("J2SE 1.4", "Merlin");         codenames.put("J2SE 5.0", "Tiger");         codenames.put("Java SE 6", "Mustang");         codenames.put("Java SE 7", "Dolphin");                  System.out.println("HashMap before sorting, random club ");         Set<Entry<String, String>> entries = codenames.entrySet();                 for(Entry<String, String> entry : entries){             System.out.println(entry.getKey() + " ==> " + entry.getValue());         }                  // Now let's form HashMap past times keys starting fourth dimension          // all you lot demand to practice is practice a TreeMap alongside mappings of HashMap         // TreeMap keeps all entries inwards sorted order         TreeMap<String, String> sorted = new TreeMap<>(codenames);         Set<Entry<String, String>> mappings = sorted.entrySet();                  System.out.println("HashMap afterwards sorting past times keys inwards ascending club ");         for(Entry<String, String> mapping : mappings){             System.out.println(mapping.getKey() + " ==> " + mapping.getValue());         }                           // Now let's form the HashMap past times values         // at that spot is no straight way to form HashMap past times values but you         // tin practice this past times writing your ain comparator, which takes         // Map.Entry object as well as suit them inwards club increasing          // or decreasing past times values.                  Comparator<Entry<String, String>> valueComparator = new Comparator<Entry<String,String>>() {                          @Override             public int compare(Entry<String, String> e1, Entry<String, String> e2) {                 String v1 = e1.getValue();                 String v2 = e2.getValue();                 return v1.compareTo(v2);             }         };                  // Sort method needs a List, hence let's starting fourth dimension convert Set to List inwards Java         List<Entry<String, String>> listOfEntries = new ArrayList<Entry<String, String>>(entries);                  // sorting HashMap past times values using comparator         Collections.sort(listOfEntries, valueComparator);                  LinkedHashMap<String, String> sortedByValue = new LinkedHashMap<String, String>(listOfEntries.size());                  // copying entries from List to Map         for(Entry<String, String> entry : listOfEntries){             sortedByValue.put(entry.getKey(), entry.getValue());         }                  System.out.println("HashMap afterwards sorting entries past times values ");         Set<Entry<String, String>> entrySetSortedByValue = sortedByValue.entrySet();                  for(Entry<String, String> mapping : entrySetSortedByValue){             System.out.println(mapping.getKey() + " ==> " + mapping.getValue());         }     }       }  Output: HashMap before sorting, random club  Java SE 7 ==> Dolphin J2SE 1.2 ==> Playground Java SE 6 ==> Mustang J2SE 5.0 ==> Tiger J2SE 1.3 ==> Kestrel J2SE 1.4 ==> Merlin JDK 1.1.4 ==> Sparkler HashMap afterwards sorting past times keys inwards ascending club  J2SE 1.2 ==> Playground J2SE 1.3 ==> Kestrel J2SE 1.4 ==> Merlin J2SE 5.0 ==> Tiger JDK 1.1.4 ==> Sparkler Java SE 6 ==> Mustang Java SE 7 ==> Dolphin HashMap afterwards sorting entries past times values  Java SE 7 ==> Dolphin J2SE 1.3 ==> Kestrel J2SE 1.4 ==> Merlin Java SE 6 ==> Mustang J2SE 1.2 ==> Playground JDK 1.1.4 ==> Sparkler J2SE 5.0 ==> Tiger

    That's all nigh how to form HashMap past times keys as well as values inwards Java. Remember, HashMap is non intended to proceed entries inwards sorted order, hence if you lot guide hold requirement to e'er proceed entries inwards a detail order, don't usage HashMap instead usage TreeMap or LinkedHashMap. This method should exclusively live used to cater adhoc needs where you lot have a HashMap from around business office of legacy code as well as you lot guide hold to form it starting fourth dimension to procedure entries. If you lot guide hold command of creating the Map initially prefer the correct implementation of Map as well as hence simply HashMap.

    Further Learning
    Java In-Depth: Become a Complete Java Engineer
    Java Fundamentals: Collections
    Data Structures as well as Algorithms: Deep Dive Using Java
    Algorithms as well as Data Structures - Part 1 as well as 2
    Data Structures inwards Java nine past times Heinz Kabutz