The findFirst() method in Java 8 is used to find the first element in a stream that matches a given predicate.

Here is an example of using findFirst() and collect() together:

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

public class Main {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");

        Optional<String> firstMatch = names.stream()
                .filter(name -> name.startsWith("C"))
                .findFirst();

        if (firstMatch.isPresent()) {
            System.out.println("First name starting with 'C': " + firstMatch.get());
        } else {
            System.out.println("No name starting with 'C' found");
        }
    }
}

In this example, we have a list of names and we want to find the first name that starts with the letter 'C'. We use the stream() method to convert the list into a stream, then we use the filter() method to filter out only the names that start with 'C'. Finally, we use the findFirst() method to find the first matching name.

The result of findFirst() is an Optional object that may or may not contain a value. We can use the isPresent() method to check if a value is present, and the get() method to retrieve the value if it is present

java8 findFirst collect

原文地址: https://www.cveoy.top/t/topic/iXpd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录