Junior — Middle
Kuidas saab välja võtta andmevoost esimese elemendi Stream API-s ilma vahemeetoditeta?
sobes.tech AI
Vastus AI-lt
In Java Stream API, to extract the first element from a stream without using intermediate methods, you can apply the terminal method findFirst(). This method returns an Optional<T>, which contains the first element of the stream if it exists.
Example:
List<String> list = List.of("apple", "banana", "cherry");
Optional<String> first = list.stream().findFirst();
first.ifPresent(System.out::println); // Will print "apple"
Therefore, findFirst() is a terminal method that does not require intermediate operations and allows you to obtain the first element from the stream.