What is the LinkedHashMap.containsValue method in Java?
A LinkedHashMap is same as HashMap, except the LinkedHashMap maintains the insertion order while the HashMap does not.
Internally, the LinkedHashMap uses the doubly-linked list to maintain the insertion order.
Read more about
LinkedHashMaphere.
What is the containsValue method in LinkedHashMap?
The containsValue method of LinkedHashMap is used to check if the specified value is present in the LinkedHashMap object.
Syntax
public boolean containsValue(Object value)
The value to be checked as present is passed as argument.
This method returns true if the value has one or more keys mapping. Otherwise, false is returned.
Code
The below example shows how to use the containsValue method.
import java.util.LinkedHashMap;class LinkedHashMapContainsValueExample {public static void main( String args[] ) {LinkedHashMap<Integer, String> map = new LinkedHashMap<>();map.put(1, "one");map.put(2, "two");System.out.println("\nChecking if the value 'one' is present : "+ map.containsValue("one"));System.out.println("\nChecking if the value 'three' is present : "+ map.containsValue("three"));}}
Explanation
In the above code:
-
In line 1, we import the
LinkedHashMapclass. -
In line 4, we create a
LinkedHashMapobject with the namemap. -
In lines 5 and 6, we use the
putmethod to add two mappings ({1=one, 2=two}) to themapobject. -
In line 7, we use the
containsValuemethod to check if themaphas a key mapping for the value"one".trueis returned as a result because the key1is mapped to the value"one" -
In line 8, we use the
containsValuemethod to check if themaphas a key mapping for the value"three".falseis returned as a result because the no key is mapped to the value"three".