Sobes.tech
Senior

How to filter even numbers from a large collection using Stream API, convert them into objects, and return any one element?

sobes.tech AI

Answer from AI

To filter even numbers, convert them into objects, and obtain any one element from a large collection using the Stream API in Java, you can use the following approach:

import java.util.*;
import java.util.stream.*;

public class Example {
    static class NumberObject {
        int value;
        NumberObject(int value) { this.value = value; }
        @Override
        public String toString() { return "NumberObject{" + "value=" + value + '}'; }
    }

    public static void main(String[] args) {
        List<Integer> numbers = IntStream.rangeClosed(1, 1_000_000).boxed().collect(Collectors.toList());

        Optional<NumberObject> anyEven = numbers.stream()
            .filter(n -> n % 2 == 0) // filter even numbers
            .map(NumberObject::new)  // convert to object
            .findAny();              // get any element

        anyEven.ifPresent(System.out::println);
    }
}

The findAny() method returns any element from the stream, which is efficient when working with large collections, especially in parallel streams.