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

No comments:

Post a Comment