Check for an element in a HashSet in Java

Java 8Object Oriented ProgrammingProgramming

To check whether an element is in a HashSet or not in Java, use the contains() method.

Create a HashSet −

HashSet hs = new HashSet();

Add elements to it −

hs.add("R");
hs.add("S");
hs.add("T");
hs.add("V");
hs.add("W");
hs.add("Y");
hs.add("Z");

To check for an element, for example, S here, use the contains() −

hs.contains("S")

The following is an example to check for an element in a HashSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet hs = new HashSet();
      // add elements to the HashSet
      hs.add("R");
      hs.add("S");
      hs.add("T");
      hs.add("V");
      hs.add("W");
      hs.add("Y");
      hs.add("Z");
      System.out.println("Set = "+hs);
      System.out.println("Is character S part of the set? "+hs.contains("S"));
      System.out.println("Is character B part of the set? "+hs.contains("B"));
   }
}

Output

Set = [R, S, T, V, W, Y, Z]
Is character S part of the set? true
Is character B part of the set? false
raja
Published on 16-Jan-2019 07:19:52
Advertisements