Core Java

Java Stream contains, containsAny and containsAll examples

The Java 8 Stream API provides various methods for operating on sequences of elements, such as filtering, mapping, and collecting. Among these operations, checking for the presence of elements can be particularly useful. Let us delve into understanding the contains, containsAny, and containsAll methods in detail.

1. contains() method

The contains() method checks if a specific element is present in the collection. The syntax of the contains() method is as follows:

boolean contains(Object o)

Let’s look at a basic example of using contains():

package com.jcg.example;

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

public class ContainsExample {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "banana", "cherry", "date");
        boolean containsApple = fruits.contains("apple");
        boolean containsMango = fruits.contains("mango");

        System.out.println("Contains 'apple': " + containsApple);
        System.out.println("Contains 'mango': " + containsMango);
    }
}

Let’s break down the example code to understand it better:

  • fruits.contains("apple") checks if “apple” is present in the fruits list.
  • fruits.contains("mango") checks if “mango” is present in the fruits list.
  • The results are printed to the console.

The output of the above code will be:

Contains 'apple': true
Contains 'mango': false

2. containsAny() method

The containsAny() method checks if any elements from one collection are present in another collection. Note that this method is not directly available in the Java 8 Stream API or standard collections but can be implemented using streams. The syntax of the contains() method is as follows:

boolean containsAny(Collection<?> c1, Collection<?> c2)

Let’s look at a basic example of using containsAny():

package com.jcg.example;

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

public class ContainsAnyExample {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "banana", "cherry", "date");
        List<String> query = Arrays.asList("mango", "banana", "pear");

        boolean containsAny = fruits.stream().anyMatch(query::contains);

        System.out.println("Contains any: " + containsAny);
    }
}

Let’s break down the example code to understand it better:

  • fruits.stream().anyMatch(query::contains) uses a stream to check if any element in the query list is present in the fruits list.
  • The result is printed to the console.

The output of the above code will be:

Contains any: true

3. containsAll() method

The containsAll() method checks if all elements from one collection are present in another collection. The syntax of the contains() method is as follows:

boolean containsAll(Collection<?> c)

Let’s look at a basic example of using containsAny():

package com.jcg.example;

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

public class ContainsAllExample {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("apple", "banana", "cherry", "date");
        List<String> query = Arrays.asList("banana", "cherry");

        boolean containsAll = fruits.containsAll(query);

        System.out.println("Contains all: " + containsAll);
    }
}

Let’s break down the example code to understand it better:

  • fruits.containsAll(query) checks if all elements in the query list are present in the fruits list.
  • The result is printed to the console.

The output of the above code will be:

Contains all: true

4. Comparison of contains(), containsAny(), and containsAll() methods

MethodDescriptionUse CasePerformance
contains()Checks if a specific element is present in the collection.Used when you need to verify the existence of a single element in a collection.
  • Time Complexity: O(n) for a List
  • Time Complexity: O(1) for a HashSet
containsAny()Checks if any elements from one collection are present in another collection. Typically implemented using streams.Useful when you need to determine if there is any overlap between two collections.
  • Performance depends on the size of both collections.
  • Uses streams, potentially less efficient for very large collections.
containsAll()Checks if all elements from one collection are present in another collection.Used when you need to ensure that a collection completely contains another collection.
  • Time Complexity: O(n * m) for Lists
  • Time Complexity: O(m) for a HashSet with a List

5. Conclusion

Understanding and utilizing methods like contains(), containsAny(), and containsAll() is essential for effective collection manipulation and querying in Java. While contains() is directly available in the Java Collection framework, containsAny() can be efficiently implemented using Java 8 Streams to check for the presence of any elements from one collection in another. Similarly, containsAll() is a powerful method to verify if a collection fully contains all elements of another collection.

These methods simplify the process of searching and validating elements within collections, making your code more readable and efficient. Leveraging the Stream API for operations like containsAny() not only enhances performance but also takes advantage of the expressive power and functional programming capabilities introduced in Java 8.

By mastering these techniques, developers can write more concise and maintainable code, ultimately leading to better performance and easier debugging. Whether you are checking for the presence of a single element or comparing multiple collections, these methods provide robust solutions for common programming tasks.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button