一、Optional流
Optional类型用来检查是否为空,确保流不会中断。
1、isPresent 是否不为空,不为空-true; 空-false
2、isEmpty 是否为空,不为空-false; 空-true
Arrays.stream(orderList)
.filter(order->!"玩具".equals(orderTypeName))
.findAny()
.map(Order::orderTypeName)
.orElse("未知订单类名称")
3、orElse 为空情况,为空时候给固定值
4、orElseGet 为空时候给个函数,构造默认值
Arrays.stream(orderList)
.filter(order->!"玩具".equals(orderTypeName))
.findAny()
.map(Order::orderTypeName)
.orElseGet(()->"anonymous");//"anonymous"常量,.orElseGet()工厂
assertNotNull(orderTypeName);
assertEquals("anonymous",orderTypeName);
5、orElseThrow 为空时候抛出异常
6、or 继续返回Optional
7、ifPresent 有值时候的处理
Arrays.stream(orderList)
.filter(order->!"玩具".equals(orderTypeName))
.findAny()
.map(Order::orderTypeName)
.ifPresent(orderTypeName->{
log.debug("orderTypeName{}",orderTypeName);
assertEquals("文具",orderTypeName);
})
8、ifPresentOrElse 有值无值都要处理
Arrays.stream(orderList)
.filter(order->!"玩具".equals(orderTypeName))
.findAny()
.map(Order::orderTypeName)
.ifPresentOrElse(
orderTypeName->{
log.debug("orderTypeName{}",orderTypeName);
assertEquals("文具",orderTypeName);
},
()->{
log.dubug("订单类名称为空");
}
)
二、Collectors收集器
toList
Set<String> orderTypeNames = orderList.stream()
.filter(order->!"玩具".equals(orderTypeName))
.findAny()
.map(Order::orderTypeName)
.collect(toList());
toSet
Set<String> orderTypeNames = orderList.stream()
.filter(order->!"玩具".equals(orderTypeName))
.findAny()
.map(Order::orderTypeName)
.collect(toSet());
toMap
Map<String,Order> orderMap = orderList.stream()
.collect(toMap(
Order::getOrderTypeNames,
order->order
));
assertTrue(orderMap.containsKey("玩具"))
//合并
TreeMap<String,Order> orderMap = stream().concat(orderList.stream(),orderList.stream())
.collect(toMap(
Order::getOrderTypeNames,
order->order,
(existing, replace)->existing,
TreeMap::new
));
assertTrue(orderMap.containsKey("玩具"))
toCollection
三、分组统计、聚合函数和其他操作符
1、聚合计算
averagingXXX 、 summingXXX 、 maxBy、 counting
//按价格取平均数、求和 价格={23,26,50}
double avg = orderList.stream().collect(averagingDouble(Order::getPrice));
double sum = orderList.stream().collect(summingInt(Order::getPrice));
//公共方法DoubleSummaryStatistics,包括求和、平均数、最大值、最小值等
DoubleSummaryStatistics stat = orderList.stream().collect(summarizingDouble(Order::getPrice));
assertEquals((23+26+50),stat.getSum());
2、分组统计
groupingBy
//分组 10一个价格段 例如:20、21为一组
val result : Map<Integer,List<Order>> = orderList.stream()
.collect(groupingBy(order->(int)Math.floor(order.getPrice() / 10)));
//两个参数例子,取每组的平均数、和、最大值、最小值等
val result : Map<Integer,DoublSummaryStatistics> = orderList.stream().collect(
groupingBy(
order->(int)Math.floor(order.getPrice() / 10),
summarizingDouble(Order:getPrice)
)
);
3、其他操作符
mapping
//mapping做类型转换
val result : Map<Integer,List<OrderDto>> = orderList.stream().collect(
groupingBy(
order->(int)Math.floor(order.getPrice() / 10),
mapping(order->new orderDto(
order.getOrderId(),
name:order.getOrderTypeName()
),
toList()
)
)
collectingAndThen
//计算价格的平均值,使用.collectingAndThen可在Collectors中做数据处理
Double avgPrice = orderList.stream()
.collect(
Collectors.collectingAndThen(
Collectors.averagingDouble(Order::getPrice),
Double::doubleValue
)
);
System.out.println(avgPrice);
joining
// 输出==》 name1 的结果:玩具文具厨具
String name1 = orderList.stream()
.map(Order::getOrderTypeName)
.collect(Collectors.joining());
System.out.println("name1 的结果:" + name1 );
// 输出==》 name2 的结果:玩具,文具,厨具
String name2 = orderList.stream()
.map(Order::getOrderTypeName)
.collect(Collectors.joining(“,”));
System.out.println("name2 的结果:" + name2 );
// 输出==》name3 的结果:{玩具,文具,厨具}
String name3 = orderList.stream()
.map(Order::getOrderTypeName)
.collect(Collectors.joining(",", "{", "}"));
//前缀是"{",后缀是"}",中间用","分隔的字符串
System.out.println("name3 的结果:" + name3 );
四、排序
sorted可以传入Comparator
List<String> list = Arrary.asList("aaa","bbb","ccc");
//正序
val abc = list.stream().sorted(String::comparaTo).collect(toList());
val abc = list.stream().sorted(Comparator.naturalOrder()).collect(toList());
//倒叙
val abc = list.stream().sorted(Comparator.reverseOrder()).collect(toList());
//按某字段排序 写法一
val abc = list.stream()
.sorted(
(a,b)->order.getOrderId().ComparaTo(order.getOrderId())
)
.collect(toList());
//按某字段排序 写法二
val abc = list.stream()
.sorted(Comparator.comparaing(
order->order.getOrderId(),
(a,b)->a.ComparaTo(b)
)
)
.collect(toList());
五、高级操作符flatMap——处理流的嵌套
1、父类对象常见的集合属性
//订单表
private static final Order[] arraryOrder = {
Order.builder()
.id("1L")
.orderCode("202206200001")
.orderTyprName("玩具")
.price(20.00)
.color(List.of("黄色","红色"))
.build(),
Order.builder()
.id("2L")
.orderCode("202206200002")
.orderTyprName("文具")
.price(10.00)
.color(List.of("粉色",“蓝色”))
.build(),
Order.builder()
.id("3L")
.orderCode("202206200003")
.orderTyprName("厨具")
.price(80.00)
.color(List.of("黑色"))
.build()
};
//使用map
val orders= orderList.stream()
.map(Order::getColor)
.peek(color->log.debug("color{}",color))
.collect(toList());
log.debug(“orders:{}”,orders);//输出=>> orders:[[黄色,红色,蓝色],[粉色,蓝色],[黑色]]
//使用flatMap 嵌套——父类对象常见的集合属性
val orders= orderList.stream()
.flatMap(order->user.getColor().stream)
.peek(color->log.debug("color{}",color))
.collect(toList());
log.debug(“orders:{}”,orders);//输出=>> orders:[黄色,红色,粉色,蓝色,黑色]
2、在流中产生了Optional元素
//嵌套——在流中产生了Optional元素
val profiles= orderList.stream()
.map(order->ThirdPartyApi.findByOrderTypeName(order.getOrderTypeName))
.flatMap(Optional::stream)//Optional空值的结果会去掉,
.peek(profile->log.debug("profile:{}",profile))
.collect(toList());
log.debug(“profiles:{}”,profiles);//输出=>> profiles:[[黄色,红色,蓝色],[粉色,蓝色],[黑色]]
六、reduce
执行归集操作,类似于Collect
//累加 初始值为0 累加器
Interger sum = orderList.stream()
.map(Order::getPrice)
.reduce(0,(Interger a, Interger b)->Interger.sum(a,b))