Junior — Middle
Kas saaks anda näite vähendusfunktsioonidest, mida kasutatakse andmete töötlemiseks Stream API-s?
sobes.tech AI
Vastus AI-lt
In the Stream API, reduction functions (reducers) are used to reduce stream elements into a single value. Main examples:
reduce(BinaryOperator<T> accumulator)— reduces elements by applying a binary operation.reduce(T identity, BinaryOperator<T> accumulator)— reduction with an initial value.
Example: calculating the sum of numbers in a list
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println(sum); // 15
Another example — concatenation of strings:
List<String> words = Arrays.asList("Java", "Stream", "API");
String result = words.stream()
.reduce("", (a, b) -> a + b + " ").trim();
System.out.println(result); // "Java Stream API"
Thus, reducers allow aggregating data from a stream into a single final value.