App下載
首頁(yè)javaoptionalJava Stream - 如何首先找到可選

Java Stream - 如何首先找到可選

我們想知道如何首先找到可選。
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("Bob", "Tom", "Jeff", "Scott", "Jennifer", "Steve");

        Optional<String> firstS = names.stream().filter(name -> name.startsWith("S")).findFirst();
        System.out.println(firstS.orElse("None found"));

        Optional<String> firstZ = names.stream().filter(name -> name.startsWith("Z")).findFirst();
        if (firstZ.isPresent()) {
            System.out.println(firstZ.get());
        } else {
            System.out.println("No Z's found");
        }
    }
}