java8 reduce 用法

用法1 没有初始值 Optional<T> reduce(BinaryOperator<T> accumulator);

其中BinaryOperator<T> extends BiFunction<T,T,T>

1
2
3
4
5
6
7
8
9
10
11
12
@FunctionalInterface
public interface BiFunction<T, U, R> {

/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);
}

未定义初始值,第一次执行的时候第一个参数 a 的值是 Stream 的第一个元素,第二个参数 b 是 Stream 的第二个元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
List<Integer> integerList = Arrays.asList(1, 2, 3, 4);
// 无初始值,第一个参数就为a,第二个为b,后续计算的值作为a
integerList.stream().reduce((a, b) -> {
System.out.println("a:" + a);
System.out.println("b:" + b);
return a + b;
}).ifPresent(System.out::println);
// 方法引用
integerList.stream().reduce(Integer::sum).ifPresent(System.out::println);

//输出结果
a:1
b:2
a:3
b:3
a:6
b:4
10
10

用法2 有初始值 T reduce(T identity, BinaryOperator<T> accumulator);

定义了初始化,从而第一次执行的时候第一个 a 参数的值是初始值 10,第二个参数 b 是 Stream 的第一个元素,方法的返回结果和初始值类型必须一致。

数字相加
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
List<Integer> integerList = Arrays.asList(1, 2, 3, 4);
// 无初始值,第一个参数就为a,第二个为b,后续计算的值作为a
System.out.println(integerList.stream().reduce(10, (a, b) -> {
System.out.println("a:" + a);
System.out.println("b:" + b);
return a + b;
}));
// 方法引用
System.out.println(integerList.stream().reduce(10, Integer::sum));

//输出结果
a:10
b:1
a:11
b:2
a:13
b:3
a:16
b:4
20
20
替换字符串中需要过滤的字段
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// java8前
private static final List<String> DANGEROUS_WORD_LIST = Arrays.asList("/t", "/n", "/r", "//");

public static String filterContent(String content) {
if (StringUtils.isEmpty(content)) {
return content;
}
for (String dangerousWord : DANGEROUS_WORD_LIST) {
content = content.replaceAll(dangerousWord, "");
}
return content;
}
// java8 reduce
public static String filterContent(String content) {
if (StringUtils.isEmpty(content)) {
return content;
}
return DANGEROUS_WORD_LIST.stream().reduce(content, (c, dangerousWord)-> c.replaceAll(dangerousWord, ""));
}