reduce
reduce 是 Java 8 中 Stream API 中的一个重要操作,它用于将流中的元素通过某种操作(通常是累积操作)来合并成一个结果。`reduce` 操作的主要作用是对流中的元素进行聚合。
reduce 操作接受一个起始值(初始种子值)和一个二元操作(BinaryOperator)作为参数,然后将流中的元素按照指定的操作顺序依次应用到这些元素上,最终得到一个单一的结果。
以下是 reduce`操作的一些常见用途和示例:
1. 计算总和或累积操作:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().reduce(0, (a, b) -> a + b); // 计算总和
2. 查找最大值或最小值:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int max = numbers.stream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b)); // 查找最大值
3. 连接字符串:
List<String> words = Arrays.asList("Hello", " ", "World", "!");
String result = words.stream().reduce("", (a, b) -> a + b); // 连接字符串
4. 自定义聚合操作:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int product = numbers.stream().reduce(1, (a, b) -> a * b); // 自定义乘法操作
5. 查找满足某个条件的元素:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> firstEven = numbers.stream().filter(n -> n % 2 == 0).reduce((a, b) -> a); // 查找第一个偶数
总之,`reduce` 操作是用于将流中的元素进行聚合和合并的功能强大的工具,它可以执行各种自定义操作,并返回一个结果。这使得它在处理集合数据时非常有用。要使用 `reduce`,您需要提供一个起始值和一个合并操作,并且可以根据需求灵活地定制聚合逻辑。
flatMap
List<> mgtList = byContractIds
.stream()
.filter(//过滤条件)
.map(//根据条件查询数据库,返回列表)
.flatMap(List::stream)
.collect(Collectors.toList());
//1使用stream()方法将firstRelations转化为一个Stream。
//2使用filter操作筛选符合条件的元素,
//3使用map操作将每个符合条件的元素转化为相应的列表
//4使用flatMap将这些列表合并成一个Stream。flatmap的参数是最终形成的一个集合
//5最后,使用collect操作将Stream中的元素收集到reList列表中。这里的collect是个收集器
//6stream().orElseThrow()可以抛异常
map
List<Long> listByFilter = userCouponService.getListByFilter(userCouponQuery)
.stream()
.map(var -> couponService.getById(var.getCouponId()))
.filter(Objects::nonNull)
.filter(var -> Objects.equals(var.getStatus(), CouponStatusEnum.VALID.getStatus()) && new Date().compareTo(var.getUsableBeginTime()) >= 0)
.map(Coupon::getId)
.collect(Collectors.toList());
- 在一个流中可以多次使用map将对象进行多次转换,如下,企业优惠卷->优惠卷->优惠卷ID。
-
在上述代码中,如果`userCouponService.getListByFilter(userCouponQuery)`返回一个空的`Stream`,那么在进行`collect(Collectors.toList())`操作时,不会报错。相反,它将返回一个空的`List`,即空列表。
Java 8 的 Stream API 允许在一个空的 Stream 上执行各种操作而不会导致异常。在这种情况下,`collect(Collectors.toList())` 操作将创建一个空的 List,而不会引发异常。这是 Stream API 的一种非常方便的行为,因为它避免了大量的空值检查和异常处理代码。
所以,如果`userCouponService.getListByFilter(userCouponQuery)`返回一个空的 Stream,代码将正常运行,并返回一个空的 List。
-
和其他api组合使用,优化代码可读性,提高清晰性,减少空值判断。
List<TmsWaybillStatus> statusList = tmsWaybillStatusService.search(filter); if (IterUtil.isNotEmpty(statusList)) { String wabillStatusId = IterUtil.getFirst(statusList).getWabillStatusId(); TmsWaybillWeighinglistFilter build = TmsWaybillWeighinglistFilter .builder() .wabillStatusId(wabillStatusId) .waybillId(model.getWaybillId()) .weighinglistType("410") .build(); tmsWaybillWeighinglistMapper.updateByBillIdAndType(build); }
tmsWaybillStatusService.search(filter) .stream() .findFirst() .map(TmsWaybillStatus::getWabillStatusId) .ifPresent(var->{ TmsWaybillWeighinglistFilter build = TmsWaybillWeighinglistFilter .builder() .wabillStatusId(var) .waybillId(model.getWaybillId()) .weighinglistType("410") .build(); tmsWaybillWeighinglistMapper.updateByBillIdAndType(build); });