Use contains() for Element Check
In this step, we will learn how to check if a specific element exists in a Java List using the contains() method. This is a common task when working with collections of data.
First, let's create a new Java file named ListContains.java in your ~/project directory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typing ListContains.java.
Now, open the ListContains.java file in the editor and add the following code:
import java.util.ArrayList;
import java.util.List;
public class ListContains {
public static void main(String[] args) {
// Create a List of strings
List<String> fruits = new ArrayList<>();
// Add some fruits to the list
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");
// Check if the list contains "Banana"
boolean hasBanana = fruits.contains("Banana");
System.out.println("Does the list contain Banana? " + hasBanana);
// Check if the list contains "Grape"
boolean hasGrape = fruits.contains("Grape");
System.out.println("Does the list contain Grape? " + hasGrape);
}
}
Let's break down this code:
import java.util.ArrayList; and import java.util.List;: These lines import the necessary classes to work with Lists.
List<String> fruits = new ArrayList<>();: This line creates a new ArrayList which is a type of List that can hold String objects.
fruits.add("...");: These lines add elements (fruit names) to our list.
fruits.contains("Banana");: This is the core of this step. The contains() method is called on the fruits list. It takes one argument, the element we want to check for. It returns true if the element is found in the list, and false otherwise.
boolean hasBanana = ...;: The result of contains() is stored in a boolean variable (hasBanana or hasGrape).
System.out.println("...");: These lines print the results to the console.
Save the ListContains.java file (Ctrl+S or Cmd+S).
Now, open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory. If not, type cd ~/project and press Enter.
Compile the Java code using the javac command:
javac ListContains.java
If there are no errors, a ListContains.class file will be created in the ~/project directory.
Finally, run the compiled Java program using the java command:
java ListContains
You should see output similar to this:
Does the list contain Banana? true
Does the list contain Grape? false
This output confirms that the contains() method correctly identified whether "Banana" and "Grape" were present in our list.