What is the LinkedHashMap.get method in Java?
A LinkedHashMap is the same as HashMap, except the LinkedHashMap maintains the insertion order, whereas the HashMap doesn’t. Internally the LinkedHashMap uses the doubly-linked list to maintain the insertion order.
Read more about
LinkedHashMaphere.
The get method of LinkedHashMap will:
-
Return the
Valueassociated with the passedkeyif there is a mapping present for the passedkey. -
Return
nullif there is no mapping present for the passedkey.
Syntax
public V get(Object key)
Code
The code below demonstrates how to use the get method.
import java.util.LinkedHashMap;class GetExample {public static void main(String[] args) {// create an LinkedHashMapLinkedHashMap<Integer, String> numbers = new LinkedHashMap<>();numbers.put(1, "One");numbers.put(2, "Two");System.out.println("The LinkedHashMap is - " + numbers);System.out.println("\nGetting value for key 1 :" + numbers.get(1));System.out.println("\nGetting value for key 5 :" + numbers.get(5));}}
In the code above, we:
-
Create a
LinkedHashMapobject with the namenumbers. -
Add two entries to the
numbers. -
Call the
getmethod for the key1. This will return the value associated with the key1. In our caseoneis returned. -
Call the
getmethod for the key5. This will returnnullbecause there is no value associated for the key5.