Sobes.tech
Junior — Middle

Can you give an example of reducer functions used in Stream API for data processing?

sobes.tech AI

Answer from AI

In the Stream API, reduce functions (reducers) are used to fold stream elements into a single value. Main examples:

  • reduce(BinaryOperator<T> accumulator) — folds elements by applying a binary operation.
  • reduce(T identity, BinaryOperator<T> accumulator) — folding with an initial value.

Example: summing 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 — concatenating 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.

Can you give an example of reducer functions used in… - sobes.tech