Java Program to check if a particular element exists in HashSet


Use the contains() method to check if a particular element exists −

Set<Integer> hs = new HashSet<Integer>();
hs.add(30);
hs.add(67);
hs.add(88);
hs.add(33);
hs.add(54);
hs.add(90);
hs.add(66);
hs.add(79);

To check for let’s say, element 89, use the contains() method −

hs.contains(89));

The following is an example to check if a particular element exists in HashSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // create hash set
      Set<Integer> hs = new HashSet<Integer>();
      hs.add(30);
      hs.add(67);
      hs.add(88);
      hs.add(33);
      hs.add(54);
      hs.add(90);
      hs.add(66);
      hs.add(79);
      System.out.println("Elements in set = "+hs);
      System.out.println("Does 89 in the set? "+hs.contains(89));
      System.out.println("Does 67 in the set? "+hs.contains(67));
   }
}

Output

Elements in set = [33, 66, 67, 54, 88, 90, 30, 79]
Does 89 in the set? false
Does 67 in the set? True

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

711 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements