Checking if a HashSet contains certain value in Java


Let’s say the following is our Integer array −

Integer arr[] = { 50, 100, 150, 200, 250, 300 };

Set the above integer array in HashSet −

Set<Integer>set = new HashSet<Integer>(Arrays.asList(arr));

Now, let us check whether the HashSet contains certain value or not −

set.contains(150)

TRUE is returned if the value is in the List, else FALSE is the return value.

Example

 Live Demo

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
   public static void main(String[] a) {
      Integer arr[] = { 50, 100, 150, 200, 250, 300 };
      Set<Integer>set = new HashSet<Integer>(Arrays.asList(arr));
      System.out.println(set.contains(200));
      System.out.println(set.contains(150));
      System.out.println(set.contains(100));
      System.out.println(set.contains(10));
   }
}

Output

true
true
true
false

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

580 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements