读者朋友晚上好。今天是清明节,是缅怀先烈的日子,也是疫情期间缅怀因疫情而牺牲的英雄的日子。
缅怀之余,今天在这里总结下笔者日常开发中常用的java8的一些简单功能,类似代码示例,以便忘记使用规则的时候快速查找和翻阅,也许会对你有所启发。
一、常用示例
Java8出来很久很久了,最大的新特性就是:Lambada表达式、函数式编程、流。这里简单罗列一下我常用的:
java8处理数据的时候,一般由中间状态和终端状态之分,中间状态指的是类似.map .filter 等操作;终端操作指的是:collect 、reduce、sorted、foreach等,终端操作意味着最后一步。
1、收集——.map
Set<Long> couponIds = objects.stream()
.map(ReceivedCoupon::getCouponId)
.collect(Collectors.toSet());
2、过滤—— .filter
List<ReceivedCouponDTO> notConsumedDTOs = receivedCouponDTOS.stream()
.filter(e -> e.getCoupon() != null)
.filter(ReceivedCouponDTO::notConsumed)
.collect(toList());
这里的谓词 notConsumed是自定义的一个返回boolean的方法,这里把方法作为一等公民传递过去
3、规约—— .reduce
BigDecimal totalAmountToReduce = notConsumedDTOs.stream()
.map(ReceivedCouponDTO::getCoupon)
.filter(coupon -> coupon.getType() == CouponTypeEnum.NOMINAL)
.map(CouponDTO::getAmount)
.reduce(BigDecimal.ZERO, (a, b) -> a.add(b));
以上代码是计算某种类型优惠券优惠金额总和
4、终端操作之一——.collect
Collectors.summingInt
Integer imUnreadTotalCount = conversations.stream()
.filter(e -> e != null)
.filter(e -> e.getUnreadMessageCount() != null)
.collect(Collectors.summingInt(ConversationInfo::getUnreadMessageCount));
Collectors.toMap
List<CouponDTO> couponDTOS = couponService.getByIds(couponIds);
Map<Long, CouponDTO> couponDTOMap = Maps.newHashMap();
if (CollectionsUtils.isNotEmpty(couponDTOS)) {
couponDTOMap = couponDTOS.stream()
.collect(Collectors.toMap(CouponDTO::getId, couponDTO -> couponDTO));
}
系统默认为我们提供了不少有用的Collector,eg:summingInt 、summingLong、summingDouble 这里可以直接运用
初次之外,还有很多很多功能:分组、排序、flatMap等等,遇到了在完善吧。