To check if a specific element is present in a list in Java, you can use the contains
method of the List interface.
In this example,
myList
with some elements.contains
method to check if the specified element is present in the list.contains
method returns true
if the element is present, otherwise false
.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> myList = new ArrayList<>();
myList.add(10); myList.add(20); myList.add(30); myList.add(40); myList.add(50);
int searchElement = 40;
boolean isPresent = myList.contains(searchElement);
System.out.println("Element presence in list: " + isPresent);
}
}
Element presence in list: true
In this example,
myList
with some string elements.contains
method to check if the specified string is present in the list.contains
method returns true
if the string is present, otherwise false
.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("apple"); myList.add("banana"); myList.add("cherry"); myList.add("date"); myList.add("elderberry");
String searchElement = "cherry";
boolean isPresent = myList.contains(searchElement);
System.out.println("Element presence in list: " + isPresent);
}
}
Element presence in list: true
In this tutorial, we learned How to check if a Specific Element is present in the List in Java language with well detailed examples.