In this post, we will see main HashMap methods in Java as well as some of its functionalities from Java 8 and earlier versions, which we could say was one of the biggest changes in Java in recent years.
What is a HashMap?
A HashMap in Java is a hash table-based implementation of the Java Map interface, which is a collection of key-value pairs.
HashMaps permit null values and do not maintain order.
Getting a value from a HashMap by Key
To obtain a value from a HashMap by its key, we can use the get(Object key) function, which will return the value associated with that key.
Update a HashMap by Key
To update a HashMap in Java, we will use put. With put, we will retrieve a value by its key and overwrite its value. “If the key does not exist, the method will create the key with its associated value:
Map<String, String> map = new HashMap<>(); map.put("apple", "green"); System.out.println(map.get("apple")); // green
If, for example, we have a map with integer values and we want to increment a value, we can do:
Map<String, Integer> map = new HashMap<>(); // NullPointerExceptionen if the key does not exist map.put("total", map.get("total") + 1);
To avoid the previous problem with null pointer in case the key does not exist, we can use containsKey():
Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < 10; i++) { if (map.containsKey("total")) { map.put("count", map.get("total") + 1); } else { map.put("total", 1); } }
From Java 8 onwards, we can make use of getOrDefault() to avoid null pointer issues by adding a default value when the key does not exist:
Map<String, Integer> map = new HashMap<>(); map.put("total", map.getOrDefault("total", 0) + 1);
Using getOrDefault() is useful in cases where we want to, for example, initialize a counter.
Remove an element in a HashMap
To remove an entry from a HashMap, we use remove, which will remove that entry from our map:
Map<String, String> map = new HashMap<>(); map.put("apple", "green"); map.remove("apple");
To know if an entry exists in a Map
Como hemos visto en un ejemplo anterior, podemos analizar si existe una key en un Map con containskey(). Containskey() nos devuelve valor false o true si existe la clave.
Map<String, Integer> map = new HashMap<>(); if (map.containsKey("total")) { return true; } else { return false; }
Using Merge in a HashMap
One of the features that came with Java 8 was the introduction of Merge(). Merge() allows us to insert a specific key/value pair into the hashmap if it is not present.
Merge() allows us to use functional programming and add or replace the value with the new value specified in the function. The Merge() function will return the value associated with the key.
Merge() allows us to combine multiple values assigned to a specific key using a function.
public static void main(String[] args) { // create a HashMap and add some values HashMap<Integer, String> oldCars= new HashMap<>(); oldCars.put(1, "MUSTANG"); oldCars.put(2, "MEGANE"); oldCars.put(3, "TOLEDO"); HashMap<Integer, String> newCars = new HashMap<>(); newCars .put(1, "A6"); newCars .put(2, "A3"); newCars .put(3, "I30"); // print map details System.out.println("OldCars: " + oldCars.toString()); System.out.println("New Cars: " + newCars .toString()); newCars .forEach((key, value) -> oldCars.merge(key,value,(v1, v2) -> v1.equalsIgnoreCase(v2) ? v1 : v1 + ", " + v2)); System.out.println("Mix new cars with oldCars: " + oldCars); }
Output:
OldCars: {1=MUSTANG, 2=MEGANE, 3=TOLEDO} New Cars: {1=A6, 2=A3, 3=I30} Mix new cars with oldCars: {1=MUSTANG, A6, 2=MEGANE, A3, 3=TOLEDO, I30}
Use Compute with HashMap
The compute(Key, BiFunction)
function of the HashMap
class allows us to update a value within a HashMap
. It updates a value for a given key and its current value. The value will be null
if the key is not found.
We can use Compute to update a value for a key.
public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("Model", "Mustang"); map.put("Brand", "Ford"); System.out.println("Map: " + map); map.compute("Model", (key, val) -> val.concat(" Blue")); map.compute("Brand", (key, val) -> val.concat(" USA")); System.out.println("New Map: " + map); }
Output:
Map: {Brand=Ford, Model=Mustang} New Map: {Brand=Ford USA, Model=Mustang Blue}
ComputeIfPresent in a HashMap
The computeIfPresent(Key, BiFunction)
function of the HashMap
class enables us to map and update the value for a specific key if that key already has an associated value (otherwise, it updates to null
).
public static void main(String[] args) { // Create a HashMap and add some values HashMap<String, Integer> count= new HashMap<>(); count.put("Yellow", 1); count.put("Black", 2); count.put("Green", 3); System.out.println("Count before :\n "+ count); count.computeIfPresent("Red", (key, val) -> val + 100); System.out.println("Count After :\n " + count); }
Output:
Count before : {Green=3, Yellow=1, Black=2} Count After : {Green=3, Yellow=1, Black=2}
ComputeIfAbsent in a HashMap
The computeIfAbsent(Key, Function)
function of the HashMap
class is very similar to computeIfPresent
. ComputeIfAbsent
is responsible for updating a value for a given key if that key is not yet associated with a value.
HashMap<String, Integer> prices = new HashMap<>(); prices.put("Mustang", 10000); prices.put("Megane", 55000); prices.put("Toledo", 44300); prices.put("I30", 53200); // print map details System.out.println("Car prices before update: " + prices.toString()); prices.computeIfAbsent("A6", k -> 2000 + 33000); prices.computeIfAbsent("A5", k -> 2000 * 34); System.out.println("Car prices after update " + prices);
Output:
Car prices before update: {Mustang=10000, Megane=55000, Toledo=44300, I30=53200} Car prices after update: {Mustang=10000, Megane=55000, Toledo=35000, I30=68000, A6=44300, A5=53200}
Methods in a HashMap
K – key
V – value
Método | Descripción |
---|---|
clear() | Remove all entries from the map. |
clone() | Return a copy of the instance. Keys and values are not cloned. |
compute(K key, BiFunction<? super K, ? super V,? extends V> remappingFunction) | Calculate a value for the specified key and its current assigned value. |
computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) | If the key is not associated with a value (or the value is null), try to calculate its value using the function passed as a parameter and add the value. |
computeIfPresent(K key, BiFunction<? super K, ? super V,? extends V> remappingFunction) | If the value of the key exists and is not null, calculate a new value using the current value. |
containsKey(Object key) | Return true if the key exists. |
containsValue(Object value) | Return true if the value exists |
entrySet() | Return a view of the values in the map. |
get(Object key) | Return the value for that key. |
isEmpty() | Return true if the map is empty |
keySet() | Return a set of the keys in the map. |
merge(K key, V value, BiFunction<? super V, ? super V,? extends V> remappingFunction) | If the key is not found, associate it with the non-null value that is provided. |
put(K key, V value) | Associate the key with the value. |
putAll(Map<? extends K,? extends V> m) | Copy all the contents from one map to the other. |
remove(Object key) | Remove the element associated with the key provided. |
size() | Return the number of key/value pairs in the map. |
values() | Return the collection of values in the map. |
Conclusion
In this article, we have seen the main methods of HashMap in Java. The use of HashMap() as well as its different methods will help us in our Java development to make use of collections.
If you need more information, you can leave us a comment or send an email torefactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!