Check if a particular value exists in Java LinkedHashMap

Java 8Object Oriented ProgrammingProgramming

Use the containsValue() method to check whether a particular value 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 value “Saturn” exists or not. For that, use the containsValue() method like this −

containsValue("Saturn")

The following is an example to check if a particular value 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("\nDoes value Saturn exist in the LinkedHashMap map? "+l.containsValue("Saturn"));
   }
}

Output

LinkedHashMap elements...
{1=Mars, 2=Earth, 3=Jupiter, 4=Saturn, 5=Venus}

Does value Saturn exist in the LinkedHashMap map? True
raja
Published on 11-Jan-2019 06:11:15
Advertisements