This method shows how to check if the element exists in the TreeSet in Java. This example also shows how to check if TreeSet contains the element using the contains method.
How to check if the specified element exists in the TreeSet in Java?
The contains
method of the TreeSet returns true if the specified element exists in the set object.
1 |
public boolean contains(Object o) |
The contains
method returns true if the TreeSet contains the specified element, false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.TreeSet; public class CheckIfElementExistsInTreeSet { public static void main(String[] args) { TreeSet<Integer> tSetOddNumbers = new TreeSet<Integer>(); tSetOddNumbers.add(1); tSetOddNumbers.add(3); tSetOddNumbers.add(5); tSetOddNumbers.add(7); tSetOddNumbers.add(9); /* * To check if the element exists in the TreeSet, use * the contains method */ //will return true as set contains element 5 System.out.println( tSetOddNumbers.contains(5) ); //will return false as set does not contain element 6 System.out.println( tSetOddNumbers.contains(6) ); } } |
Output
1 2 |
true false |
What about the TreeSet of custom class objects?
The contains
method works for TreeSet of custom class elements too. But remember, if the TreeSet elements are objects of a custom class, then the custom class must implement the Comparable interface or a custom Comparator must be provided in the TreeSet constructor. If not, the code throws java.lang.ClassCastException when we try to add elements to the TreeSet 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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import java.util.TreeSet; class Student implements Comparable<Student>{ private int id; public Student(int id){ this.id = id; } public int getId(){ return this.id; } public String toString(){ return "Student -> " + getId(); } public int compareTo(Student otherStudent) { return this.getId() - otherStudent.getId(); } } public class CheckIfElementExistsInTreeSet { public static void main(String[] args) { TreeSet<Student> tSetStudents = new TreeSet<Student>(); tSetStudents.add(new Student(501)); tSetStudents.add(new Student(502)); tSetStudents.add(new Student(503)); /* * this will print true as the student with id 502 exists * in the TreeSet */ System.out.println( tSetStudents.contains(new Student(502)) ); /* * This will print false as the student with id 505 does * not exist */ System.out.println( tSetStudents.contains(new Student(505)) ); } } |
Output
1 2 |
true false |
As we can see from the output, the contains
method worked just fine for the objects of a custom class.
This example is a part of the Java TreeSet Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 TreeSet