What is HashMap?
HashMap is one of the implementation class of Map interface of java collections. HashMap stores data as (key,value) pair, where key is unique in Map. HashMap is a class available from java.util package. HashMap is not order collection class because it doesn't returns elements as inserting order. null will be allowed as value multiple times, but null for key will be allowed only one time. By default HashMap is not synchronized.Creating HashMap with default constructor
public class HashMapExample { public static void main(String args[]) { // creating HashMap object HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); // bid is key and b is the value books.forEach((bid, b) -> { System.out.println("Book id: " + bid + "Book name: " + b); }); } }
HashMap is not a thread safe, because it is not synchronized. But HashTable is thread safe
Creating HashMap with capacity and load factor
First we try to understated what is capacity and load factor
capacity means size of HashMap means number of elements to store in it.
Load factor means, HashMap is based on HashTable, if we mentions load factor value as 0.7 then if the size of Hash Table filled 70% then date will be stored in a new Hash Table where its size will be doubled to the original hash table.
HashMap default capacity is 16 and load factor is 0.75
In the above code we have created HashMap with out passing capacity and load factor, that means HashMap created with the capacity 16 and load factor 0.75 .HashMap<Integer, String> booksNew= new HashMap<Integer, String>(10, 0.5f);
Creating HashMap from existing HashMap
Now we will create new HashMap from existing HashMap object
HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); // creating HashMap object from existing object (book) HashMap<Integer, String> bookFrom= new HashMap<Integer, String>(books);In line 8 we have passed an object which created in line 1.
Adding elements
There are different ways to add elements into HashMap objectAdd new element
How to add new element to existing HashMap object, we can use put(k,v) method to add new element to existing HashMap object
HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference");
Add all elements of existing
Hashmap How to adding all elements of existing HashMap into another existing HashMap, we can use putAll(hashMapObject) method add all elements of one HashMap object into another HashMap object.// creating HashMap object HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); HashMap<Integer, String> booksNew = new HashMap<Integer, String>(10, 0.5f); booksNew.putAll(books);
Check key presence before adding
How to add new element if the key is not available in HashMap object: by using pufIfAbsent() method we can add (key,value) if key is not added already into HashMap// creating HashMap object HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); books.putIfAbsent(3, "New MySQl Book"); // not added because 3 is already added as a key books.putIfAbsent(4, "WEb Tech book");
Retrieving elements from HashMap
There are different methods to read keys only, values only and entry set ie pair of key & value.
Reading keys only
How to read only keys from HashMap, we can use keySet() method which returns Set object of key type.// creating HashMap object HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); Set<Integer> ks=books.keySet(); ks.forEach(k->{System.out.print(k+":");});
Getting only values
We can use values() method which returns Collection object of values type// creating HashMap object HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); Collection<String> v = books.values(); v.forEach(va -> { System.out.println(va); });
Retrieve entrysets (key,values)
We can use entrySet() method which returns Set object of Entity objects having key type and value type of HashMapSet<Entry<Integer, String>> e = books.entrySet(); e.forEach(en -> { Integer k = en.getKey(); String v = en.getValue(); System.out.println("Key: " + k + " value: " + v); });
get value by key
we can use get(key) method to get the value associated with the provided key, returns null if key is not avaialable in.
// creating HashMap object HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); System.out.println(books.get(2));In line 8 we have invoked get() method to get the value of key with 2
getOrDefault()
this method will return value if the key is has value or returns default value provided
// creating HashMap object HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); System.out.println(books.getOrDefault(3, "NO Book")); System.out.println(books.getOrDefault(4, "NO Book"));In the above in line 8 it will print MYSQL server glory as a result but in line 9 it will print NO Book because there is no value associated for the key 4.
Delete elements from HashMap
remove(key) method
We can use remove(key) method to delete an element associated with the provided key , and returns the value of key which is being removed.
String val=books.remove(2); System.out.println("removed: "+val);
remove(key,value) method
This method removes an element with the pair key and value, and return true if element removed
// creating HashMap object HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); boolean vv=books.remove(3, "MYSQL server glory"); System.out.println("element removed: "+ vv);
Update / Replace value
There are different ways to update the values of HashMap
replace(key,newValue)
This method will replace the old value associated with the key will be replaced with the newValue passed, and returns old value of the key associated, if value was not associated with key this method will return null.// creating HashMap object HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); String oldValue=books.replace(1, "New java book"); System.out.println("old value: "+oldValue); System.out.println("New value: "+books.get(1));
replace(key, oldValue, newValue)
This method will return will true or false , will return true if old value is associated and replace with new value of the key else will return false.
boolean ov=books.replace(2, "HTML complete guide", "New HTML complete guide"); System.out.println("Updated the value of key 2 "+ov);
replaceAll(function)
We can apply for the logic on the value of HashMap before replacing the value
// creating HashMap object HashMap<Integer, String> books = new HashMap<Integer, String>(); // adding book into books map books.put(1, "Java Complete Reference"); books.put(2, "HTML complete guide"); books.put(3, "MYSQL server glory"); books.replaceAll(( key,oldValue)->{return oldValue.toUpperCase();}); books.forEach((k,v) -> { System.out.println("Key is: "+k +"and value is "+ v); });In the above code we happy applied the logic to change the value into Uppercase
ReCompute values
By using replaceAll() we can apply additional logic on total elements of HashMap, but if we want to apply logic on the value of a particular key then we can use compute methods
compute() method
this method is for applying additional on a value of provided key
-
compute
public V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
- Parameters:
key
- key with which the specified value is to be associatedremappingFunction
- the function to compute a value- Returns:
- the new value associated with the specified key, or null if none
computeIfAbsent() method
This method can be useful to execute a logic if an element with the key is not available in HashMap
-
computeIfAbsent
public V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
If the specified key is not already associated with a value (or is mapped tonull
), attempts to compute its value using the given mapping function and enters it into this map unlessnull
.If the function returns
null
no mapping is recorded. If the function itself throws an (unchecked) exception, the exception is rethrown, and no mapping is recorded. The most common usage is to construct a new object serving as an initial mapped value or memoized result, as in:map.computeIfAbsent(key, k -> new Value(f(k)));
Or to implement a multi-value map,
Map<K,Collection<V>>
, supporting multiple values per key:map.computeIfAbsent(key, k -> new HashSet<V>()).add(v);
- Parameters:
key
- key with which the specified value is to be associatedmappingFunction
- the function to compute a value- Returns:
- the current (existing or computed) value associated with the specified key, or null if the computed value is null
computeIfPresent() method
If the value for the specified key is present and non-null then we can execute a logic before adding new value to specified key
-
computeIfPresent
public V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)
If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.If the function returns
null
, the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.- Specified by:
computeIfPresent
in interfaceMap<K,V>
- Parameters:
key
- key with which the specified value is to be associatedremappingFunction
- the function to compute a value- Returns:
- the new value associated with the specified key, or null if none
Post a Comment
Post a Comment