This example shows how to check any element is or not in set.This example also shows How to check given element is present in TreeSet or not with the help of TreeSet.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
Now , We use contains() method to check any element is or not in set. Let’s see this by code.
import java.util.Set;
import java.util.TreeSet;
public class ContailsElement {
public static void main(String[] args) {
Set<String> ts = new TreeSet<String>();
ts.add("mumbai");
ts.add("delhi");
ts.add("kolkata");
ts.add("chandigarh");
ts.add("dehradun");
// print treeset
System.out.println(" ts ="+ts);
System.out.println(ts.contains("java"));
System.out.println(ts.contains("delhi"));
System.out.println(ts.contains("php"));
}
}
Output:
ts =[chandigarh, dehradun, delhi, kolkata, mumbai]
false
true
false
In this post we have seen how to How to find does TreeSet contains elements or not . We have seen also TreeSet contains() method example . This example is part of Java TreeSet Examples .