Thursday, July 4, 2024
HomeLanguagesJavaChecking if Element Exists in LinkedHashSet in Java

Checking if Element Exists in LinkedHashSet in Java

The Java.util.LinkedHashSet.contains() method is used to check whether a specific element is present in the LinkedHashSet or not. So basically it is used to check if a Set contains any particular element. The contains a method of the LinkedHashSet class returns true if the specified element is found in the LinkedHashSet object.

Example:

Given List: [1, 2, 3, 4]

Input : FirstSearch = 1, SecondSearch = 6
Output: True False

Syntax:

Hash_Set.contains(Object element)

Return Type: If the element found in the then it returns true, else false.

Parameters: The parameter element is of the type of LinkedHashSet. This is the element that needs to be tested if it is present in the set or not.

Example:

Java




// Checking if element exists in LinkedHashSet in Java
import java.util.LinkedHashSet;
public class LinkedHashSetContainsExample {
  
    public static void main(String[] args)
    {
  
        LinkedHashSet<String> lhSetColors
            = new LinkedHashSet<String>();
  
        lhSetColors.add("red");
        lhSetColors.add("green");
        lhSetColors.add("blue");
  
        /*
         * To check if the LinkedHashSet contains the
         * element, use the contains method.
         */
  
        // this will return true as the "red" element exists
        System.out.println(lhSetColors.contains("red"));
  
        // this will return true as the "white" element does
        // not exists
        System.out.println(lhSetColors.contains("white"));
    }
}


Output

true
false
Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments