Loading

Java8 Stream流示例

流式处理

+--------------------+ +------+ +------+ +---+ +-------+
| stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect|
+--------------------+ +------+ +------+ +---+ +-------+

filter

filter(Objects::nonNull);// 过滤空元素
filter(u -> StringUtils.isNotEmpty(u.getId()))

sorted

// 先按height升序,再按age降序;reverseOrder代表倒序
sorted(Comparator.comparing(User::getHeight).thenComparing(User::getAge, Comparator.reverseOrder()))
// 空的放在最后面,还有个nullsFirst是放在最前面
sorted(Comparator.comparing(User::getHeight, Comparator.nullsLast(Comparator.naturalOrder()))
// 处理字符串类型的数字
sorted(Comparator.comparing(User::getHeight, Comparator.comparingDouble(Double::parseDouble))

map

map(User::getId)
map(String::valueOf)
map(i -> i*i)
// 嵌套list合并成一个list
flatMap(Collection::stream)
// 获取price,从字符串转成BigDecimal,累加
map(OrderModel::getPrice).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add)

collect

collect(Collectors.toList())
collect(Collectors.joining(","));// 以","拼接各元素
collect(Collectors.toMap(User::getId, u -> u))
// 以Function.identity()代替u -> u,出现重复key时,使用第一个,指定map的实现类
collect(Collectors.toMap(User::getId, Function.identity(), (k1, k2) -> k1, LinkedHashMap::new))
// 无序分组
collect(Collectors.groupingBy(User::getCityId));
// 有序分组
collect(Collectors.groupingBy(User::getCityId, LinkedHashMap::new, Collectors.toList()));

其他

list.toArray();
Arrays.asList(arr);
Arrays.stream(arr)
// list调用sort可以直接进行排序
list.sort(Comparator.comparing(User::getHeight).reversed().thenComparing(User::getAge));

boolean = anyMatch(u -> u.getType() == 1)
boolean = noneMatch(u -> u.getType() == 1)
count()
distinct()
forEach()
findAny()
findFirst().ifPresent(x -> x)
mapToInt(x -> x).summaryStatistics();// 统计
taskList.removeIf(model -> model.getMachineId() == 25);
posted @ 2022-09-08 16:09  多久会在  阅读(30)  评论(0)    收藏  举报