Check if an element exists in TreeSet in Java
How to search for objects stored in a TreeSet? ArrayList implements the java.util.List which provides the get(int index) to retrieve an object with its index. Unlike List, TreeSet implements the interface java.util.Set which does not allow indexing of objects, so it cannot be accessed directly.However, the two collections share the contains() to check if the list (in our case TreeSet) contains a specific element. You can browse TreeSet with Iterator and test equality with the condition if(o1.equals(o2)) until it reaches the desired element. Here we are talking about Set, so the elements are mixed and don't have a precise index.
import java.util.Iterator;Compiling and executing this code results in this:
import java.util.TreeSet;
public class search_element {
public static void main(String[] args) {
// creating TreeSet
TreeSettset = new TreeSet ();
// populate TreeSet
tset.add("abc");
tset.add("bcd");
tset.add("cde");
tset.add("def");
tset.add("efg");
String e = "def";
// check for the existence of a specific element in TreeSet
boolean exists = tset.contains(e);
System.out.println(e+" exists in treeset? "+exists);
String e2 = "eee";
exists = tset.contains(e2);
System.out.println(e2+" exists in treeset? "+exists);
Iteratoriterator = tset.iterator();
// search for the element and test equality with equals
while (iterator.hasNext()){
String obj = iterator.next();
if(obj.equals(e))
System.out.println("the object "+e+" exists in the list");
}
}
}
def exists in treeset? trueReferences:
eee exists in treeset? false
the def object exists in the list
StackOverFlow: How come Java's TreeSet has no get() method?