LinkedHashMap in Java
In the last blog, we learned about the HashMap class and its methods. If you want to learn more about HashMap, visit HashMap in Java. In this blog, we will go through the class called LinkedHashMap.
LinkedHashMap
LinkedHashMap works the same as HashMap with additional features. HashMap provides the advantage of quick insertion, deletion, and search but the track and the order of the insertion is never maintained. But the opposite is the case with LinkedHashMap, LinkedHashMap provides the ability where elements can be accessed in their insertion order. In order to use the LinkedHashMap we must import the package called java.util.
Creating LinkedHashMap
e.g.
Output
Methods of LinkedHashMap
- put()
- putAll()
- putIfAbsent()
- entrySet()
- keySet()
- values()
- get()
- getOrDefault()
- remove()
put() method adds or insert the elements in the Hashmap.
putAll() method adds or inserts all the key-value mappings from the specified Map to the HashMap.
putIfAbsent() method inserts the specified value with the specified key in the map only if it is not already present in the hashmap.
Example of LinkedHashMap using the above three methods
Output
entrySet() method returns a set of all the key-value mapping of the map.
The keySet() method is used to return a set view of the keys present in this map.
values() method returns the view of all the values present in the entries of the hashmap.
Example of LinkedHashMap using the above three methods
Output
get() method returns the value of the specified key in the hashmap.
The getOrDefault() method returns the value associated with the given key. If the key cannot be discovered, it returns the supplied default value.
remove() method removes or deletes the specified values with the associated specified keys from the map.
Example for LinkedHashMap using the above two methods
Output