Check if a particular element exists in Java LinkedHashSet

Java 8Object Oriented ProgrammingProgramming

Use the contains() method to check if a specific element exists in LinkedHashSet or not.

Let us first create a LinkedHashSet and add some elements −

LinkedHashSet<String> l = new LinkedHashSet<String>();
l.add(new String("1"));
l.add(new String("2"));
l.add(new String("3"));
l.add(new String("4"));
l.add(new String("5"));
l.add(new String("6"));
l.add(new String("7"));

Now, check whether it contains element “5” or not −

l.contains("5")

The following is an example to check if a particular element exists in LinkedHashSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      LinkedHashSet<String> l = new LinkedHashSet<String>();
      l.add(new String("1"));
      l.add(new String("2"));
      l.add(new String("3"));
      l.add(new String("4"));
      l.add(new String("5"));
      l.add(new String("6"));
      l.add(new String("7"));
      System.out.println("LinkedHashSet elements...");
      System.out.println(l);
      System.out.println("Does 5 exist in the LinkedHashSet elements? "+l.contains("5"));
   }
}

Output

LinkedHashSet elements...
[1, 2, 3, 4, 5, 6, 7]
Does 5 exist in the LinkedHashSet elements? True
raja
Published on 30-Jan-2019 07:19:09
Advertisements