Iterate Through Hashmap and Get All Key Value Pairs Where Value Is Greater Than 1
The HashMap in Java is one of the most popular Collection classes among Java programmers. After my article on How HashMap works in Java, which describes the theory part of Java HashMap and becomes hugely popular among Java programmers, I thought to share how to use HashMap in Java with some fundamental HashMap examples, but couldn't do that earlier and it was slipped. The HashMap is a data structure, based on hashing, which allows you to store an object as a key-value pair, an advantage of using HashMap is that you can retrieve objects on constant time i.e. O(1) if you know the key.
The HashMap class implements a Map interface and supports Generics from Java 1.5 release, which makes it type-safe. There are a couple of more Collections, which provides similar functionalities like HashMap, which can also be used to store key-value pair.
Hashtable is one of them, but Hashtable is synchronized and performs poorly in a single-threaded environment. See Hashtable vs HashMap for complete differences between them.
Another one, relatively new is ConcurrentHashMap, which provides better performance than Hashtable in a concurrent environment and should be preferred. See the difference between ConcurrentHashMap and HashMap for detailed differences.
In this Java tutorial, we will see different examples of HashMap, like adding and removing entries, iterating over Java HashMap, checking size map, finding if a key or value exists on Map, and various other examples, which we used frequently.
Btw, if you are new to the Java Programming world then I also suggest you go through a comprehensive online Java course like The Complete Java Masterclass by Tim Buchalaka on Udemy to fill the gaps in your learning because Java is vast and a structured course like this will accelerate your learning. This is also the most comprehensive (80+ hours) and most up-to-date course to learn Java in depth.
10 Java HashMap Examples for Beginners
Before going to see these examples, few things to note about Java HashMap.It's not synchronized, so don't share your HashMap among multiple threads.
Another common cause of the error is clearing Map and reusing it, which is perfectly valid in a single-threaded environment but if done in a multi-threaded environment can create subtle bugs.
1. Create and add objects in HashMap Example
In the first example of HashMap, we will create and add an object to our Map. Always use Generics, if you are not working in Java 1.4. The following code will create HashMap with keys of type String and values of type Integer with default size and load factor.
HashMap < String, Integer > cache = new HashMap < String, Integer > ();
alternatively, you can create HashMap by copying data from another Map or Hashtable as shown in the below example:
Hashtable < Integer, String > source = new Hashtable < Integer,String > (); HashMap < Integer, String > map = new HashMap(source);
You can also supply load factor (percentage of size, which if filled trigger resizes of HashMap) and initial capacity while creating an instance by using the overloaded constructor provided in API.
Adding elements is also called the put operation in HashMap and requires a key and a value object.
Here is an example of adding key and value in Java HashMap:
map.put ( 21, "Twenty One" ); map.put ( 21.0, "Twenty One" ); / /this will throw compiler error because 21.0 is not integer
If you want to learn more, you can further seeJava Collections: Fundamentals course by Java Champion Richard Burton, from Pluralsight to learn more about HashMap. It's a good course and available for free when you signup for a 10-day free trial.
2. Retrieving value from HashMap Example
Another basic example is the retrieving value from HashMap. In order to retrieve values, we need to know the key object. let's use the key inserted in the last example, forgetting the value back from Map. get(key) method is used to get value from HashMap :
Integer key = 21; String value = map.get(key); System.out.println("Key: " + key + " value: " + value); Output: Key : 21 value : Twenty One
See how does get() method internally works in Java to learn more about retrieving mapping in Java. The article explains how get() method uses equals() and hashCode() to retrieve value object even in case of collision.
3. Iterating over HashMap Example
Another way to get value from HashMap is by iterating over the whole Map. Sometimes we do want to loop through the whole map and perform operations on each key-value pair, we can use Iterator for that purpose.
In order to use an Iterator, we first need Set of keys, which can be retrieved using themap.keySet() method. By the way, there are multiple ways to loop through Map in Java, see here for 4 ways to loop HashMap in Java.
Here is an example 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 can also refer toCore Java for Impatient book by Cay S. Horstmann to learn more about iterating over Map in Java, it also covers new techniques of iteration using the forEach() method in Java 8.
4. Size and Clear method Example in HashMap
Two fundamental examples of HashMap are finding out how many elements are stored in Map, known as the size of Map, and clearing HashMap to reuse. Java Collection API provides two convenient methods called size() and clear() to perform these operations on java.util.HashMap, here is a 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 can reuse Map by clearing it, but be careful if it's been shared between multiple threads without proper synchronization. Since you may need to prevent other threads from accessing the map when it's getting clear. I suggest not doing it until you have a very good reason for doing it.
Java HashMap Example 5 and 6: ContainsKey and ContainsValue Example
In this example of Java HashMap, we will learn how to check if Map contains a particular object as a key or value. java.util.HashMap provides convenient methods like containsKey(Object key) and containsValue(Object value) which can be used for checking the existence of any key value in HashMap.
Here is a code example :
System .out.println( "Does HashMap contains 21 as key: " + map.containsKey( 21 ) ) ; System .out.println( "Does HashMap contains 21 as value: " + map.containsValue( 21 ) ) ; System .out.println( "Does HashMap contains Twenty One as value: " + map.containsValue( "Twenty One" ) ) ; Output : Does HashMap contains 21 as key: true Does HashMap contains 21 as value: false Does HashMap contains Twenty One as value: true
7. Checking if HashMap is empty in Java Example
In this Map example, we will learn how to check if HashMap is empty in Java. There are two ways to find out if Map is empty, one is using thesize() method, if the size is zero means Map, is empty.
Another way to check if HashMap is empty is using a more readable isEmpty() method which returns true if Map is empty.
Here is a code example :
boolean isEmpty = map.isEmpty( ) ; System .out.println( "Is HashMap is empty: " + isEmpty) ; Output : Is HashMap is empty: false
If you want to learn more about HashMap and Java Collections framework, I also suggest you checkJava Collections from basics to Advanced courses on Udemy. It's a great course to master the Java Collection framework.
8. Removing Objects from HashMap Example
Another common example of Java HashMap is removing entries or mapping from Map. The java.util.HashMap provides theremove(Object key) method, which accepts the key and removes mapping for that key.
This method returns null or the value of the entry, just removed. You can also see these Java collection courses from Pluralsight to learn more about removing or replacing existing mapping in HashMap and also learn Java collection in depth.
Anyway, here is a code example of removing key values from HashMap:
Integer key = 21 ; Object value = map.remove(key) ; System .out.println( "Following value is removed from Map: " + value) ; Output : Following value is removed from Map : Twenty One
9. Java HashMap Example- Sorting HashMap in Java
HashMap is an unsorted Map in Java, neither key nor value is sorted. If you want to sort HashMap then you can sort it based upon key or value, see how to sort HashMap on keys and values for a full code example.
Alternatively, you can use SortedMap in Java, like TreeMap. TreeMap has a constructor which accepts Map and can create a Map sorted on the natural order of key or any custom sorting order defined by Comparator.
The only thing that is key should be naturally comparable and their compareTo() method shouldn't throw an exception. Just to remind there are no Collections.sort() method defined for Map is only for List and its implementation e.g. ArrayList or LinkedList.
So any sorting for Map requires SortedMap or custom code for sorting on either key or value. here is a code example of sorting HashMap in Java by using TreeMap in the natural order 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}
10. Synchronized HashMap in Java Example
You need to synchronize HashMap if you want to use it in a multi-threaded environment. If you are running on Java 1.5 and above consider using ConcurrentHashMap in place of synchronized HashMap because it provides better concurrency.
If your project is still on JDK 1.4 then you got to use either Hashtable or synchronized Map.
The Collections.synchronizedMap(map) is used to synchronize HashMap in Java. See here for a full code example. This method returns a thread-safe version of Map and all map operation is serialized.
Thanks for reading this article if you find these Java HashMap examples useful then please share them with your friends and colleagues. If you have any questions or feedback then please drop me a note.
P. S. - If you are new to Java programming and looking for a free course to learn Java in a structured way then you can also check this Java Tutorial for Complete Beginners(FREE) course on Udemy. It's completely free and more than 1 million developers have joined this course. You just need a free Udemy account to join the course.
Iterate Through Hashmap and Get All Key Value Pairs Where Value Is Greater Than 1
Source: https://www.java67.com/2013/02/10-examples-of-hashmap-in-java-programming-tutorial.html
0 Response to "Iterate Through Hashmap and Get All Key Value Pairs Where Value Is Greater Than 1"
Post a Comment