java8 Optional使用 stream filter多级过滤
java8 Optional使用 stream filter多级过滤
package com.example.core.mydemo.java8; public class MyModel { private String couponCode; private Integer orderType; private String orderNo; private String frameNo; private Integer couponStatus = 0; //默认 public Integer getCouponStatus() { return couponStatus; } public void setCouponStatus(Integer couponStatus) { this.couponStatus = couponStatus; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public String getFrameNo() { return frameNo; } public void setFrameNo(String frameNo) { this.frameNo = frameNo; } public String getCouponCode() { return couponCode; } public void setCouponCode(String couponCode) { this.couponCode = couponCode; } public Integer getOrderType() { return orderType; } public void setOrderType(Integer orderType) { this.orderType = orderType; } } package com.example.core.mydemo.java8; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class ListTest { public static void main(String[] args) { List<MyModel> list = new ArrayList(); MyModel model = new MyModel(); model.setCouponCode("111111"); model.setCouponStatus(1); model.setOrderType(1); list.add(model); model = new MyModel(); model.setCouponCode("22222"); model.setCouponStatus(0); model.setOrderType(2); list.add(model); int orderType = 1; Optional<MyModel> optional = Optional.ofNullable(list).orElseGet(ArrayList::new).stream().filter(x -> x.getOrderType() == orderType).filter(x ->x.getCouponStatus() == 0).findFirst(); MyModel model3 = optional.orElse(null); if(model3 != null) { String couponId = model3.getCouponCode(); //关联订单号 System.out.println("couponId="+couponId); }else{ System.out.println("未找到未使用的记录"); } } }