Check if a particular key exists in Java LinkedHashMap


Use the containsKey() method to check whether a particular key exists in LinkedHashMap or not.

Create a LinkedHashMap −

LinkedHashMap<Integer, String> l = new LinkedHashMap<Integer, String>();
l.put(1, "Mars");
l.put(2, "Earth");
l.put(3, "Jupiter");
l.put(4, "Saturn");
l.put(5, "Venus");

Now, let’s say we need to check whether key 4 exists or not. For that, use the containsKey() method like this −

l.containsKey(4)

The following is an example to check if a particular key exists in LinkedHashMap −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      LinkedHashMap<Integer, String> l = new LinkedHashMap<Integer, String>();
      l.put(1, "Mars");
      l.put(2, "Earth");
      l.put(3, "Jupiter");
      l.put(4, "Saturn");
      l.put(5, "Venus");
      System.out.println("LinkedHashMap elements...");
      System.out.println(l);
      System.out.println("
Does key 4 exist in the LinkedHashMap elements? "+l.containsKey(4)); } }

Output

LinkedHashMap elements...
{1=Mars, 2=Earth, 3=Jupiter, 4=Saturn, 5=Venus}
Does key 4 exist in the LinkedHashMap elements? True

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements