Answers for "reduce in stream"

2

reduce in stream in java

// Identity – an element that is the initial value of the reduction operation and the default result if the stream is empty
// Accumulator – a function that takes two parameters: a partial result of the reduction operation and the next element of the stream
// Combiner – a function used to combine the partial result of the reduction operation when the reduction is parallelized or when there's a mismatch between the types of the accumulator arguments and the types of the accumulator implementation

import java.util.*; 
import java.util.stream.*;

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers
  .stream()
  .reduce(0, (subtotal, element) -> subtotal + element); // Didn't use a combiner here

// A combiner should be used when objects are used in accumulator parameters
// Only then, it works

List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result = users.stream()
  .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
// Integer::sum is a combiner which is a function for the desired operation.
Posted by: Guest on June-08-2021
2

java reduce array

Arrays.stream(array).reduce((str1, str2) -> str1 + str2);
Posted by: Guest on September-09-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language