Check if a particular value exists in Java TreeSet


The contains() method is used to check if a particular value exists.

First, create a TreeSet and add elements −

TreeSet<String> set = new TreeSet<String>();
set.add("34");
set.add("12");
set.add("67");
set.add("54");
set.add("76");
set.add("49");

Use the contains() method to check if a value exist or not i.e. 12 in this case −

set.contains("12")

The following is an example to check whether a particular value exist or not −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> set = new TreeSet<String>();
      set.add("34");
      set.add("12");
      set.add("67");
      set.add("54");
      set.add("76");
      set.add("49");
      System.out.println("TreeSet elements...");
      Iterator<String> i = set.iterator();
      while(i.hasNext()) {
         System.out.println(i.next());
      }
      System.out.println("Does element 12 exist in the TreeSet ? " + set.contains("12"));
   }
}

Output

TreeSet elements...
12
34
49
54
67
76
Does element 12 exist in the TreeSet ? true

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements