How to find does HashSet contains elements or not

In this post we will see how to check any element is or not in set. We can check given element is present in hashset or not with the help of Hashset.contains() method. This method returns true if this set contains the specified element.we can say returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).

Syntax :

public boolean contains(Object o) {

}

Parameters: o element whose presence in this set is to be tested
Returns Value: true if this set contains the specified element

import java.util.HashSet;
import java.util.Set;

public class ContailsElement {

public static void main(String[] args) {

Set<String> hs = new HashSet<String>();
hs.add("java");
hs.add("php");
hs.add("html");
hs.add("javascript");
hs.add("mysql");

//print hashset
System.out.println("hashset = "+hs);

System.out.println(hs.contains("java"));
System.out.println(hs.contains("HTml"));
System.out.println(hs.contains("delhi"));

}

}

Output :

hashset = [javascript, php, html, java, mysql]

true

false

false

A Guide to HashSet                                                                                                          Java Doc – HashSet

Leave a Reply

Your email address will not be published. Required fields are marked *

− 8 = 2