Checking if a HashSet contains certain value in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 25-Apr-2019 09:40:05
Advertisements