📌  相关文章
📜  在java代码示例中减少流

📅  最后修改于: 2022-03-11 14:52:26.908000             🧑  作者: Mango

代码示例1
// 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 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 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.