Check If an Element Exists in Java TreeSet Example

Java TreeSet Examples

<__ This Java example shows how to check whether an element is contained in the Java TreeSet using contains() method.

Check If an Element Exists in Java LinkedHashSet Example

In the following example, we are checking whether TreeSet contains a "Ramesh" student object or not:
package com.javaguides.collections.treesetexamples;

import java.util.TreeSet;

public class AccessTreeSetElementsExample {
    public static void main(String[] args) {
        TreeSet < String > students = new TreeSet < > (String.CASE_INSENSITIVE_ORDER);


        System.out.println("Students TreeSet : " + students);

        // Finding the size of a TreeSet
        System.out.println("Number of elements in the TreeSet : " + students.size());

        // Check if an element exists in the TreeSet
        String name = "Ramesh";
        if (students.contains(name)) {
            System.out.println("TreeSet contains the element : " + name);
        } else {
            System.out.println("TreeSet does not contain the element : " + name);



Students TreeSet : [Cruise, John, Ramesh, Stark]
Number of elements in the TreeSet : 4
TreeSet contains the element : Ramesh