1. Introduction

The LinkedHashSet class in Java is part of the Java Collections Framework and inherits from the HashSet class. It introduces the feature of maintaining the order of elements in which they were inserted. In this post, we will explore how to use the contains method with LinkedHashSet to check if a specific element is present in the set.

2. Program Steps

1. Create a LinkedHashSet and populate it with elements.

2. Use the contains method to check if the set contains specific elements.

3. Print the results.

3. Code Program

import java.util.LinkedHashSet;

public class LinkedHashSetContains {

    public static void main(String[] args) {
        // Step 1: Create a LinkedHashSet and populate it with elements
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
        linkedHashSet.add("Apple");
        linkedHashSet.add("Banana");
        linkedHashSet.add("Cherry");

        // Step 2: Use the contains method to check if the set contains specific elements
        boolean containsApple = linkedHashSet.contains("Apple");
        boolean containsGrapes = linkedHashSet.contains("Grapes");

        // Step 3: Print the results
        System.out.println("Does the LinkedHashSet contain Apple? " + containsApple);
        System.out.println("Does the LinkedHashSet contain Grapes? " + containsGrapes);
    }
}

Output:

Does the LinkedHashSet contain Apple? true
Does the LinkedHashSet contain Grapes? false

4. Step By Step Explanation

Step 1: We initialize a LinkedHashSet named linkedHashSet and add three elements to it: "Apple", "Banana", and "Cherry".

Step 2: We use the contains method of the LinkedHashSet class to check if the set contains the strings "Apple" and "Grapes". The method returns a boolean value indicating the presence or absence of the specified element.

Step 3: We print out the results. The output indicates that "Apple" is present in the LinkedHashSet, while "Grapes" is not, hence it prints true for "Apple" and false for "Grapes".