Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

linkedhashmap
java
communitycreator

What is the LinkedHashMap.containsKey method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

A LinkedHashMap is the same as HashMap, except that 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 LinkedHashMap here.

What is the containsKey method in LinkedHashMap?

The containsKey method of LinkedHashMap is used to check if a value is mapped to the specified key.

Syntax


public boolean containsKey(Object key)

Argument

The key to being checked for presence is passed as an argument.

Return value

This method returns true if the key has a mapping. Otherwise, false will be returned.

Code

The below example shows how to use the containsKey method.

import java.util.LinkedHashMap;
class LinkedHashMapContainsKeyExample {
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 key '1' has mapping: "+ map.containsKey(1));
System.out.println("\nChecking if the key '3' has mapping: "+ map.containsKey(3));
}
}

Explanation

In the above code:

  • In line 1, we import the LinkedHashMap class.

  • In line 2, we create a LinkedHashMap object with the name map.

  • In line 5 and 6, we use the put method to add two mappings ({1=one, 2=two}) to the map object.

  • In line 7, we use the containsKey method to check if the map has a mapping for the key 1. true is returned as a result because the map has a mapping for the key 1.

  • In line 8, we use the containsKey method to check if the map has a mapping for the key 3. true is returned as a result because the map has a mapping for the key 3.

RELATED TAGS

linkedhashmap
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring