LinkedList contains() Method in Java
Last Updated :
16 Dec, 2024
Improve
In Java, the contains() method of LinkedList is used to check whether an element is present in a LinkedList or not. It takes the element as a parameter and returns True if the element is present in the list.
Syntax of Java LinkedList contains() Method
boolean contains(Object element);
- Parameter: The parameter element is of type LinkedList. This parameter refers to the element whose occurrence is needed to be checked in the list.
- Return Value: The method returns True if the element is present in the LinkedList otherwise it returns False.
Example: Here, we use the contains() method to check if the element is present in the LinkedList or not.
// Java programm to Demonstrate the
// use of contains() in LinkedList
import java.util.LinkedList;
public class Geeks {
public static void main(String args[]) {
LinkedList<String> l = new LinkedList<>();
// Use add() method to
// add elements in the list
l.add("Geeks");
l.add("for");
l.add("Geeks");
l.add("10");
l.add("20");
System.out.println("LinkedList: " + l);
// Check if the list contains "20"
System.out.println("\nThe List contains '20': "
+ l.contains("20"));
// Check if the list contains "Hello"
System.out.println(
"The List contains 'Hello': "
+ l.contains("Hello"));
// Check if the list contains "Geeks"
System.out.println(
"The List contains 'Geeks': "
+ l.contains("Geeks"));
}
}
Output
LinkedList: [Geeks, for, Geeks, 10, 20] The List contains '20': true The List contains 'Hello': false The List contains 'Geeks': true