Check for an element in a HashSet in Java


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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements