Java LinkedHashSet contains()

In this guide, you will learn about the LinkedHashSet contains() method in Java programming and how to use it with an example.

1. LinkedHashSet contains() Method Overview


The contains() method of the LinkedHashSet class in Java is used to check whether a specific element is present in the set or not. It returns true if the set contains the specified element, otherwise, it returns false.


public boolean contains(Object o)


- o: The element whose presence in this set is to be tested.

Key Points:

- The contains() method is used to check the presence of a single element in the LinkedHashSet.

- The method will return true if the specified element is found in the set; otherwise, it will return false.

- The method accepts any Object as its parameter.

- The contains() method works in constant time, O(1), for this implementation, making it efficient.

- If the object passed to contains() is not of the correct type or is null, the method will return false.

2. LinkedHashSet contains() Method Example

import java.util.LinkedHashSet;

public class LinkedHashSetContainsExample {

    public static void main(String[] args) {
        LinkedHashSet<String> fruitSet = new LinkedHashSet<>();

        // Adding elements to the LinkedHashSet

        // Printing the LinkedHashSet
        System.out.println("LinkedHashSet: " + fruitSet);

        // Checking the presence of elements
        System.out.println("Contains Apple? " + fruitSet.contains("Apple"));
        System.out.println("Contains Orange? " + fruitSet.contains("Orange"));
        System.out.println("Contains null? " + fruitSet.contains(null));


LinkedHashSet: [Apple, Banana, Cherry]
Contains Apple? true
Contains Orange? false
Contains null? false


In this example, we have a LinkedHashSet containing some elements. 

We then use the contains() method to check the presence of various elements in the set, including a null value. The output demonstrates that the method accurately identifies whether the specified elements are present in the LinkedHashSet or not, returning true or false accordingly.