1. Introduction

In Java, finding an element in a List can be performed using various methods. One common approach is using the contains() method provided by the List interface. Additionally, the Java Stream API can also be utilized for more advanced searching conditions. This tutorial illustrates how to find an element in a List in Java.

2. Program Steps

1. Create a List of String elements.

2. Print the original List.

3. Use the contains() method to check if the List contains a specific element.

4. Use the stream() API and the anyMatch() method for more advanced searching.

5. Print the result of the searches.

3. Code Program

import java.util.Arrays;
import java.util.List;

public class FindInList {

    public static void main(String[] args) {

        // Step 1: Create a List of String elements
        List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry", "Date");

        // Step 2: Print the original List
        System.out.println("Original List: " + fruits);

        // Step 3: Use the contains() method to check if the List contains a specific element
        boolean containsApple = fruits.contains("Apple");
        System.out.println("Contains Apple: " + containsApple);

        // Step 4: Use the stream() API and the anyMatch() method for more advanced searching
        boolean containsOrange = fruits.stream().anyMatch("Orange"::equalsIgnoreCase);
        System.out.println("Contains Orange: " + containsOrange);
    }
}

Output:

Original List: [Apple, Banana, Cherry, Date]
Contains Apple: true
Contains Orange: false

4. Step By Step Explanation

Step 1: A List named fruits is initialized with some String elements representing fruit names.

Step 2: The original List, fruits, is printed to the console.

Step 3: The contains() method of the List interface is used to check if the List fruits contains the String "Apple". The result is stored in a boolean variable containsApple and printed to the console.

Step 4: The stream() API is used along with the anyMatch() method for advanced searching. It checks if the List fruits contains the String "Orange" ignoring case differences. The result is stored in a boolean variable containsOrange and printed to the console.

In the given example, the List fruits contains "Apple" but does not contain "Orange", hence the output shows Contains Apple: true and Contains Orange: false.