The LinkedHashSet.contains()
method in Java is used to check if a particular element is present in a LinkedHashSet
.
Table of Contents
- Introduction
contains
Method Syntax- Examples
- Checking for Elements in a LinkedHashSet
- Handling Elements Not in the LinkedHashSet
- Conclusion
Introduction
The LinkedHashSet.contains()
method is a member of the LinkedHashSet
class in Java. It allows you to check if a specific element is present in the LinkedHashSet
.
contains Method Syntax
The syntax for the contains
method is as follows:
public boolean contains(Object o)
- The method takes a single parameter
o
of typeObject
, which represents the element to be checked in theLinkedHashSet
. - The method returns a boolean value:
true
if the element is present in the set.false
if the element is not present in the set.
Examples
Checking for Elements in a LinkedHashSet
The contains
method can be used to check if specific elements are present in a LinkedHashSet
.
Example
import java.util.LinkedHashSet;
public class ContainsExample {
public static void main(String[] args) {
// Creating a LinkedHashSet of Strings
LinkedHashSet<String> animals = new LinkedHashSet<>();
// Adding elements to the LinkedHashSet
animals.add("Lion");
animals.add("Tiger");
animals.add("Elephant");
// Checking if certain elements are present in the LinkedHashSet
boolean containsLion = animals.contains("Lion");
boolean containsMonkey = animals.contains("Monkey");
// Printing the results
System.out.println("Contains Lion: " + containsLion);
System.out.println("Contains Monkey: " + containsMonkey);
}
}
Output:
Contains Lion: true
Contains Monkey: false
Handling Elements Not in the LinkedHashSet
The contains
method returns false
if the element is not present in the LinkedHashSet
.
Example
import java.util.LinkedHashSet;
public class NotContainsExample {
public static void main(String[] args) {
// Creating a LinkedHashSet of Strings
LinkedHashSet<String> animals = new LinkedHashSet<>();
// Adding elements to the LinkedHashSet
animals.add("Lion");
animals.add("Tiger");
animals.add("Elephant");
// Checking if an element that is not in the LinkedHashSet
boolean containsGiraffe = animals.contains("Giraffe");
// Printing the result
System.out.println("Contains Giraffe: " + containsGiraffe);
}
}
Output:
Contains Giraffe: false
Conclusion
The LinkedHashSet.contains()
method in Java provides a way to check if a specific element is present in a LinkedHashSet
. By understanding how to use this method, you can efficiently verify the presence of elements in your collections. The method ensures that you can quickly check for the existence of elements, making it useful for various validation and conditional operations in your Java applications.