Java Math.random() method
Following is the example of Java Math.random() method:

#batman#dc#dc comics#bruce wayne#dick grayson#tim drake#batfamily#batfam#dc fanart




seen from Austria
seen from United Kingdom
seen from Saudi Arabia

seen from Netherlands

seen from Netherlands

seen from United States
seen from Germany
seen from Canada
seen from Germany

seen from United States

seen from T1
seen from Russia

seen from United States
seen from China
seen from Yemen
seen from United States
seen from Spain

seen from United Kingdom

seen from Ukraine

seen from Canada
Java Math.random() method
Following is the example of Java Math.random() method:
Java Map Example by using comparingByKey()
Following is the non-generic Java map example:
Generic Java Map Example
Following is the generic Java map example:
Non-Generic Java Map Example
Following is the non-generic Java map example:
HashMap methods Java
HashMap Class in Java stores the data in the form of key-value pairs where the key data should be unique. We can access the values based on the corresponding key data. HashMap is present in Java's Collection framework and is part of java.util package. It works on the principle of the Hashing technique.
Java HashMap Hierarchy
The HashMap class in Java extends the Abstract class AbstractMap and implements the Map interface as shown below.
HashMap structure and working principle
HashMap in Java works on the principle of hashing technique. In hashing, we use hash functions to link key and value in a HashMap. The HashMap stores the key-value pairs in the form of an array of nodes where each entry is considered as a bucket. A bucket is nothing but an element in an array. Each node has 3 values: Key, value, and link to the next node. When more than 1 node shares the same index, it represents a linked list. Every node is mapped to an index in the bucket which is calculated using hashcode().
HashMap Performance
Performance of HashMap in Java depends on the below parameters: - Initial Capacity - It denotes how many buckets a HashMap can store when it is initialized. By default, it is 16 key-value pairs - Load Factor - It is the percentage of capacity that needs to be increased. By default, it is 0.75 - Threshold - This is the product of load factor and capacity whose default value is 12 (16*0.75) - Rehashing - This is the process of doubling the capacity after it reaches a threshold value.
Java HashMap declaration
To use HashMap in Java, we need to import java.util.HashMap package. The syntax is as given below: HashMap map = new HashMap(); KeyType - It is the type of key data.Eg: String or Integer ValueType - It is the type of value data. Eg: String or Integer
HashMap Features
Below are the features of HashMap in Java: - Stores values corresponding to each key - Contains only unique keys - Does not allow duplicate keys but can have duplicate values - It does not maintain any order which means the order in which data is inserted is not the same as the order in which it is retrieved. - It is non-synchronized
Java HashMap Class Constructors
HashMap supports 4 different constructors as you can see in the below table:
HashMap Methods
Java HashMap supports all the methods that belong to Map interface along with the methods mentioned in the below table
HashMap Exceptions
It throws the below exceptions in Java: - ConcurrentModificationException - IllelgalMonitorStateException - NullPointerException - InterruptedException - IllegalArgumentException
Adding Elements to HashMap
As you can see in the below example, first we create a HashMap named 'student' with the key of String type and value of Integer type. We then add individual key-value pairs using the put method. You can notice in the output that the order in which the elements are retrieved is not the same as the order in which it was inserted. Next, we create a second HashMap named 'stu' and then add 2 key-value pairs. This we then add to the 'student' map using the putAll method. import java.util.HashMap; public class HashMapAdd { public static void main(String args) { HashMap student = new HashMap(); student.put("Arthi", 100); student.put("Dev", 105); student.put("Banu",102); student.put("Rishi", 108); System.out.println("Elements in student map:"); System.out.println(student); HashMap stu = new HashMap(); stu.put("Ravi",110); stu.put("Tejas", 112); System.out.println("Elements in stu map:"); System.out.println(stu); student.putAll(stu); System.out.println("Elements in student map after invoking putAll method:"); System.out.println(student); } } Elements in student map: {Dev=105, Banu=102, Rishi=108, Arthi=100} Elements in stu map: {Ravi=110, Tejas=112} Elements in student map after invoking putAll method: {Dev=105, Ravi=110, Tejas=112, Banu=102, Rishi=108, Arthi=100}
Check if the map contains a specific key or value
We use containsKey method to check if a specific key is present in the map or not. In this case, Dev is present and hence it returns true and Ravi is not present and hence returns false. Similarily, containsValue method checks if a specific value is present. Here, 102 is present but 110 is not present and hence returns false. import java.util.HashMap; public class HashMapAdd { public static void main(String args) { HashMap student = new HashMap(); student.put("Arthi", 100); student.put("Dev", 105); student.put("Banu",102); student.put("Rishi", 108); System.out.println("Elements in student map:"); System.out.println(student); System.out.println(student.containsKey("Dev")); System.out.println(student.containsKey("Ravi")); System.out.println(student.containsValue(102)); System.out.println(student.containsValue(110)); } } Elements in student map: {Dev=105, Banu=102, Rishi=108, Arthi=100} true false true false
Remove and Replace a key-value pair
Here, we create a hashmap in Java of Integer and String type to store languages. We replace the 2nd value with new data and replace the 3rd value if the specific key-value pair is present in the map using replace() method. Then, we remove the 3rd element using the key and remove the 1st element using key-value using the remove() method. import java.util.HashMap; public class RemoveHashMap { public static void main(String args) { HashMap lang = new HashMap(); lang.put(1, "Java"); lang.put(2, "C"); lang.putIfAbsent(3, "C++"); System.out.println(lang); lang.replace(2, "PHP"); System.out.println(lang); lang.replace(3, "C++", "JavaScript"); System.out.println(lang); lang.remove(3); System.out.println(lang); lang.remove(1, "Java"); System.out.println(lang); } } {1=Java, 2=C, 3=C++} {1=Java, 2=PHP, 3=C++} {1=Java, 2=PHP, 3=JavaScript} {1=Java, 2=PHP} {2=PHP}
Example of clear and empty methods
HashMap in Java uses the clear() method to clear the mapping of key-value pairs in the map and isEmpty method checks if the map is empty. The 1st output is false since mapping is present and 2nd output is true since the map does not have any key-value pairs after invoking the clear() method. import java.util.HashMap; public class RemoveHashMap { public static void main(String args) { HashMap lang = new HashMap(); lang.put(1, "Java"); lang.put(2, "C"); System.out.println(lang.isEmpty()); lang.clear(); System.out.println(lang.isEmpty()); } } false true
Iterating through HashMap elements using entrySet
To retrieve the individual key-value pairs of HashMap in Java, we can use the entrySet method of HashMap along with the Entry method of the Map interface using a for-each loop. The Entry method of the Map interface has built-in methods such as geyKey() to get the key and getValue() to get the corresponding value. We can use the size() method to get the size of the map. import java.util.HashMap; import java.util.Map; public class IterateHashMap { public static void main(String args) { HashMap cityState = new HashMap(); cityState.put("Bangalore", "Karnataka"); cityState.put("Chennai", "TamilNadu"); cityState.put("Madurai", "TamilNadu"); cityState.put("Mumbai", "Maharashtra"); System.out.println("Size of map is : " + cityState.size()); for(Map.Entry m : cityState.entrySet()) { System.out.println(m.getKey() + " : " + m.getValue()); } } } Size of map is : 4 Chennai : TamilNadu Madurai : TamilNadu Mumbai : Maharashtra Bangalore : Karnataka
Loop through elements using keySet() and values()
Another way to loop through Hashmap elements is by using the keySet() method. Using this, we can get a set of all keys separately as seen in the below example. To get all values separately, we can use the values() method and print them in for loop. Using keySet, we can also print the key-value pairs by iterating in for loop by using get() method to get the corresponding values. import java.util.HashMap; import java.util.Map; public class IterateHashMap { public static void main(String args) { HashMap cityState = new HashMap(); cityState.put("Bangalore", "Karnataka"); cityState.put("Chennai", "TamilNadu"); cityState.put("Madurai", "TamilNadu"); cityState.put("Mumbai", "Maharashtra"); System.out.println("Printing only keys:"); for(String s : cityState.keySet()) { System.out.println(s); } System.out.println(); System.out.println("Printing only values: "); for(String c : cityState.values()) { System.out.println(c); } System.out.println(); System.out.println("Printing both key-value pairs:"); for(String v : cityState.keySet()) { System.out.println("Key: " + v + " | value: " + cityState.get(v)); } } } Printing only keys: Chennai Madurai Mumbai Bangalore Printing only values: TamilNadu TamilNadu Maharashtra Karnataka Printing both key-value pairs: Key: Chennai | value: TamilNadu Key: Madurai | value: TamilNadu Key: Mumbai | value: Maharashtra Key: Bangalore | value: Karnataka
Conclusion
In this tutorial, you have learned about HashMap and its different methods along with various examples. Reference Read the full article