Check if a particular element exists in Java LinkedHashSet



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
Updated on: 2019-07-30T22:30:24+05:30

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements