In this post we will see examples on how to check if Hashset contains an element/object.
For this we will use the boolean contains(Object o) method.
Example : Check if HashSet contains the Element/Object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.kscodes.sampleproject; import java.util.HashSet; import java.util.Set; public class HashSetConatinsExample { public static void main(String[] args) { Set<String> hashSet = new HashSet<>(); hashSet.add("Java"); hashSet.add("Spring"); hashSet.add("Hibernate"); hashSet.add("JavaScript"); System.out.println("Does HashSet contain - 'JQuery' :: " + hashSet.contains("JQuery")); System.out.println("Does HashSet contain - 'Java' :: " + hashSet.contains("Java")); } } |
Output
1 2 |
Does HashSet contain - 'JQuery' :: false Does HashSet contain - 'Java' :: true |