Java 8 – Check if a List Contains an Element

Introduction

Checking if a list contains a specific element is a common task in programming, especially when working with collections of data. Whether you need to verify the presence of an item in a list of numbers, strings, or custom objects, Java 8 provides a powerful and concise way to perform this operation using the Stream API. In this guide, we’ll explore how to check if a list contains an element using Java 8 Streams, covering different types of lists including primitive types and custom objects.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Checking if a List of Integers Contains an Element
    • Checking if a List of Strings Contains an Element
    • Checking if a List of Custom Objects Contains an Element
  • Advanced Considerations
  • Conclusion

Problem Statement

The task is to create a Java program that:

  • Accepts a list of elements.
  • Checks if the list contains a specific element.
  • Outputs whether the element is present in the list.

Example 1:

  • Input: List of integers [1, 3, 7, 0, 5], check for 7
  • Output: true

Example 2:

  • Input: List of custom Student objects, check for a Student object with a specific name and age.
  • Output: true or false depending on the presence of the element.

Solution Steps

  1. Input List: Start with a list of elements that can either be hardcoded or provided by the user.
  2. Check for Element Using Streams: Use the anyMatch() method to check if the list contains the specified element.
  3. Display the Result: Print whether the element is present in the list.

Java Program

Checking if a List of Integers Contains an Element

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

/**
 * Java 8 - Check if a List of Integers Contains an Element
 * Author: https://www.rameshfadatare.com/
 */
public class CheckElementInList {

    public static void main(String[] args) {
        // Step 1: Take input list
        List<Integer> numbers = Arrays.asList(1, 3, 7, 0, 5);

        // Step 2: Check if the list contains the element '7'
        boolean contains = numbers.stream()
                                  .anyMatch(num -> num == 7);

        // Step 3: Display the result
        System.out.println("List contains 7: " + contains);
    }
}

Output

List contains 7: true

Explanation

  • The stream() method is used to create a stream from the list of integers.
  • The anyMatch() method checks if any element in the stream matches the specified condition (num == 7).
  • The result is a boolean value, which is printed to indicate whether the list contains the element 7.
  • The output shows that the list does indeed contain the element 7, returning true.

Checking if a List of Strings Contains an Element

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

/**
 * Java 8 - Check if a List of Strings Contains an Element
 * Author: https://www.rameshfadatare.com/
 */
public class CheckStringInList {

    public static void main(String[] args) {
        // Step 1: Take input list
        List<String> fruits = Arrays.asList("apple", "banana", "orange");

        // Step 2: Check if the list contains the element 'banana'
        boolean contains = fruits.stream()
                                 .anyMatch(fruit -> fruit.equals("banana"));

        // Step 3: Display the result
        System.out.println("List contains 'banana': " + contains);
    }
}

Output

List contains 'banana': true

Explanation

  • The stream() method is used to create a stream from the list of strings.
  • The anyMatch() method checks if any element in the stream matches the specified condition (fruit.equals("banana")).
  • The result is a boolean value, which is printed to indicate whether the list contains the element "banana".
  • The output shows that the list does contain the element "banana", returning true.

Checking if a List of Custom Objects Contains an Element

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

/**
 * Java 8 - Check if a List of Custom Objects Contains an Element
 * Author: https://www.rameshfadatare.com/
 */
public class CheckCustomObjectInList {

    public static void main(String[] args) {
        // Step 1: Take input list of custom objects
        List<Student> students = Arrays.asList(
                new Student("Raj", 25),
                new Student("Anita", 30),
                new Student("Vikram", 22)
        );

        // Step 2: Check if the list contains a student named 'Raj' with age 25
        boolean contains = students.stream()
                                   .anyMatch(student -> student.getName().equals("Raj") && student.getAge() == 25);

        // Step 3: Display the result
        System.out.println("List contains student 'Raj' with age 25: " + contains);
    }
}

// Custom class Student
class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Output

List contains student 'Raj' with age 25: true

Explanation

  • The list of Student objects is processed to check if it contains a student with a specific name and age.
  • The anyMatch() method is used with a custom condition to determine if any Student object matches the criteria (student.getName().equals("Raj") && student.getAge() == 25).
  • The result is a boolean value, which is printed to indicate whether the list contains the specified Student.
  • The output shows that the list does contain a Student named "Raj" who is 25 years old, returning true.

Advanced Considerations

  • Handling Empty Lists: If the list is empty, anyMatch() will return false, as there are no elements to match the condition.

  • Case Sensitivity: When working with strings, remember that equals() is case-sensitive. If you need a case-insensitive comparison, consider using equalsIgnoreCase() or converting both the list elements and the target value to lowercase before comparing.

  • Custom Comparators: When working with custom objects, ensure that the equals() and hashCode() methods are correctly overridden if you rely on these methods for comparisons.

Conclusion

This guide provides methods for checking if a list contains a specific element using Java 8 Streams, covering both simple lists like integers and strings, as well as more complex lists like custom objects. Java 8 Streams offer a powerful and concise way to perform this operation, making your code more readable and maintainable. Depending on your specific use case, you can easily apply the techniques demonstrated in this guide to determine whether a list contains a particular element.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top