Junior — Middle
How can a single value be extracted from a data stream in the Stream API?
sobes.tech AI
Answer from AI
To extract a specific value from a data stream in the Stream API, you can use terminal operations that return a particular element or aggregate. For example:
findFirst()— returns the first element in the stream, wrapped in an Optional.findAny()— returns any element from the stream (useful for parallel streams).max()andmin()— return the maximum or minimum value according to a given comparator.reduce()— allows reducing the stream to a single value, such as a sum or concatenation.
Example of extracting the first element from a list:
List<String> list = Arrays.asList("apple", "banana", "cherry");
Optional<String> first = list.stream().findFirst();
first.ifPresent(System.out::println); // Will output "apple"
Thus, to obtain a specific value from a stream, you should use an appropriate terminal operation that returns a particular element or aggregate.