本文介绍java 8 Stream流的常用高频api,通过实战级别的案例进行演示。实现结合实际业务、开发需要来应用技术,不让技术讲解枯燥无味,带来技术落地成生产力的价值。
1. 思考,stream 的多个操作,相当于几个for循环,实际执行了几次循环?
List<String> collect = strings.stream()
// peek1
.peek(e -> out.println("Original Element: " + e))
// filter
.filter(e -> e.length() > 3)
// peek2
.peek(e -> out.println("Filtered value: " + e))
//map
.map(String::toUpperCase)
//peek3
.peek(e -> out.println("Mapped value: " + e))
// collect
.collect(Collectors.toList());
2. Lambda 的 peek 和 forEach 区别
peek 返回值是和之前流泛型相同的流, 多用于打印中间操作时元素数据
forEach 没有返回值, 无法继续使用点语法操作
/**
* @author zhangcq
* @version 1.0.0
* @title
* @date 2022/6/9 13:50
*/
public class PeekAndForEachExample {
public static void main(String[] args) {
PrintStream out = System.out;
final List<String> strings
= Arrays.asList("one", "two", "three", "four");
List<String> result = new ArrayList<>();
/**~~~~~~~重点看这里~~~~~~~~~~~~~~~~~~~~**/
for (String e : strings) {
// peek1
out.println("Original Element: " + e);
// filter
if (e.length() > 3) {
// peek2
out.println("Filtered value: " + e);
//map
e = e.toUpperCase();
//peek3
out.println("Mapped value: " + e);
// collect
result.add(e);
}
}
System.out.println("stream collect: " + result);
out.println("Final Results: " + strings);
out.println("~~~~~~~~~~~~~~~~~~~~~");
List<String> collect = strings.stream()
// peek1
.peek(e -> out.println("Original Element: " + e))
// filter
.filter(e -> e.length() > 3)
// peek2
.peek(e -> out.println("Filtered value: " + e))
//map
.map(String::toUpperCase)
//peek3
.peek(e -> out.println("Mapped value: " + e))
// collect
.collect(Collectors.toList());
System.out.println("stream collect: " + collect);
out.println("Final Results: " + strings);
}
}
3. Reduce用法之BigDecimal求和
/**
* @author zhangcq
* @version 1.0.0
* @title
* @date 2022/6/9 16:46
*/
public class ReduceExample {
public static void main(String[] args) {
List<BigDecimal> list = new ArrayList<>();
list.add(BigDecimal.valueOf(1.1));
list.add(BigDecimal.valueOf(1.2));
list.add(BigDecimal.valueOf(1.3));
list.add(BigDecimal.valueOf(1.4));
BigDecimal decimal = list.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println("reduce: " + decimal);
DoubleSummaryStatistics doubleSummaryStatistics = list.stream().mapToDouble(o -> o.doubleValue()).summaryStatistics();
System.out.println("doubleSummaryStatistics: " + doubleSummaryStatistics.getAverage());
System.out.println("doubleSummaryStatistics: " + doubleSummaryStatistics.getSum());
}
}
4 map 和 flatMap用法
/**
* @author zhangcq
* @version 1.0.0
* @title
* @date 2022/6/9 17:21
*/
public class MapAndFlatMapExample {
public static void main(String[] args) {
UserAbAutoHandinDo do1 = UserAbAutoHandinDo.builder().list(Arrays.asList(1, 2, 3)).build();
UserAbAutoHandinDo do2 = UserAbAutoHandinDo.builder().list(Arrays.asList(4, 5, 6)).build();
UserAbAutoHandinDo do3 = UserAbAutoHandinDo.builder().list(Arrays.asList(7, 8, 9)).build();
UserAbAutoHandinDo do4 = UserAbAutoHandinDo.builder().list(Arrays.asList(10, 11, 12)).build();
List<UserAbAutoHandinDo> userAbAutoHandinDos = Arrays.asList(do1, do2, do3, do4);
userAbAutoHandinDos.stream().map(o -> o.getList());
Stream<Integer> integerStream = userAbAutoHandinDos.stream().flatMap(o -> o.getList().stream());
System.out.println(integerStream.collect(Collectors.toList()));
String[] strings = {"Hello", "World"};
List<String> collect = Arrays.stream(strings)
.map(str -> str.split(""))
.flatMap(splitArray -> Arrays.stream(splitArray))
.collect(Collectors.toList());
System.out.println(collect);
}
}
5. sortedExample
/**
* @author zhangcq
* @version 1.0.0
* @title
* @date 2022/6/9 17:21
*/
public class SortedExample {
public static void main(String[] args) {
UserAbAutoHandinDo do1 = UserAbAutoHandinDo.builder().list(Arrays.asList(1, 2, 3)).build();
UserAbAutoHandinDo do2 = UserAbAutoHandinDo.builder().list(Arrays.asList(4, 5, 6)).build();
UserAbAutoHandinDo do3 = UserAbAutoHandinDo.builder().list(Arrays.asList(7, 8, 9)).build();
UserAbAutoHandinDo do4 = UserAbAutoHandinDo.builder().list(Arrays.asList(10, 11, 12)).build();
List<UserAbAutoHandinDo> userAbAutoHandinDos = Arrays.asList(do1, do2, do3, do4);
System.out.println("~~~~~~~没有短路操作不执行~~~~");
userAbAutoHandinDos.stream().sorted((x, y) -> x.getList().get(0).compareTo(y.getList().get(0))).peek(
o -> System.out.println(o.getList().get(0))
);
System.out.println("~~~~~~~有短路操作执行~~~~Comparator.comparing(keySelector)");
userAbAutoHandinDos.stream().sorted(Comparator.comparing(x -> x.getList().get(0)))
.peek(o -> System.out.println(o.getList().get(0)))
.collect(Collectors.toList());
System.out.println("~~~~~乱序之后~~有短路操作执行~~~~Comparator.comparing(keySelector)");
userAbAutoHandinDos = Arrays.asList(do1, do4, do2, do3);
userAbAutoHandinDos.stream().sorted(Comparator.comparing(x -> x.getList().get(0))).peek(
o -> System.out.println(o.getList().get(0))
).collect(Collectors.toList());
}
}
6 Collecotrs之toMap 和 groupingBy
/**
* @author zhangcq
* @version 1.0.0
* @title
* @date 2022/6/9 17:53
*/
public class CollectorsExample1 {
public static void main(String[] args) {
UserAbAutoHandinDo do1 = UserAbAutoHandinDo.builder().userId("aaaa").list(Arrays.asList(1, 2, 3)).build();
UserAbAutoHandinDo do2 = UserAbAutoHandinDo.builder().userId("bbbb").list(Arrays.asList(4, 5, 6)).build();
UserAbAutoHandinDo do3 = UserAbAutoHandinDo.builder().userId("cccc").list(Arrays.asList(7, 8, 9)).build();
UserAbAutoHandinDo do4 = UserAbAutoHandinDo.builder().userId("dddd").list(Arrays.asList(10, 11, 12)).build();
System.out.println("~~~~~~~maxBy~~~~");
List<UserAbAutoHandinDo> userAbAutoHandinDos = Arrays.asList(do1, do2, do3, do4);
Optional<UserAbAutoHandinDo> collect = userAbAutoHandinDos.stream().collect(Collectors.maxBy(Comparator.comparing(x -> x.getList().get(0))));
System.out.println(collect.get().getList());
System.out.println("~~~~~~~ToMap~~~~");
Map<Integer, String> collect2 = userAbAutoHandinDos.stream().collect(Collectors
.toMap(x -> x.getList().get(0) % 2, //keyMapper
x -> x.getUserId(), // valueMapper
(x, y) -> x + "+" + y) // mergeFunction
);
System.out.println(JSON.toJSONString(collect2, true));
System.out.println("~~~~~~~groupingBy~~~~");
Map<Integer, List<UserAbAutoHandinDo>> collect1 = userAbAutoHandinDos.stream().collect(Collectors
.groupingBy(x -> x.getList().get(0) % 2));
System.out.println(JSON.toJSONString(collect1, true));
}
}
~~~~~~~maxBy~~~~
[10, 11, 12]
~~~~~~~ToMap~~~~
{
0:"bbbb+dddd",
1:"aaaa+cccc"
}
~~~~~~~groupingBy~~~~
{
"0": [
{
"list": [
4,
5,
6
],
"userId": "bbbb"
},
{
"list": [
10,
11,
12
],
"userId": "dddd"
}
],
"1": [
{
"list": [
1,
2,
3
],
"userId": "aaaa"
},
{
"list": [
7,
8,
9
],
"userId": "cccc"
}
]
}
7. Collectors之partitionBy
/**
* @author zhangcq
* @version 1.0.0
* @title
* @date 2022/6/9 17:53
*/
public class CollectorsExample2 {
public static void main(String[] args) {
UserAbAutoHandinDo do1 = UserAbAutoHandinDo.builder().userId("aaaa").list(Arrays.asList(1, 2, 3)).build();
UserAbAutoHandinDo do2 = UserAbAutoHandinDo.builder().userId("bbb").list(Arrays.asList(4, 5, 6)).build();
UserAbAutoHandinDo do3 = UserAbAutoHandinDo.builder().userId("ccc").list(Arrays.asList(7, 8, 9)).build();
UserAbAutoHandinDo do4 = UserAbAutoHandinDo.builder().userId("dddd").list(Arrays.asList(10, 11, 12)).build();
System.out.println("~~~~~~~partitioningBy~~~~");
List<UserAbAutoHandinDo> userAbAutoHandinDos = Arrays.asList(do1, do2, do3, do4);
Map<Boolean, Map<Integer, List<UserAbAutoHandinDo>>> collect = userAbAutoHandinDos.stream().collect(Collectors.partitioningBy(o -> o.getUserId().length() > 3, Collectors.groupingBy(o -> o.getList().get(0) % 2))
);
System.out.println(JSON.toJSONString(collect, true));
}
}