java8 实现List对象去重

举例说明:以用户优惠券为例,全部优惠券去重,可用优惠券去重,以及全部优惠券去除可用优惠券


import java.util.stream.Collectors;
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;


// 全部优惠券去重
List<CouponVo> allCouponUniqueList = userAllCouponList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(CouponVo::getId))), ArrayList::new));
// 可用优惠券去重
List<CouponVo> canUseCouponUniqueList = canUseCouponList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(CouponVo::getId))), ArrayList::new));
// 不可用优惠券
List<CouponVo> notCanUseCouponList = allCouponUniqueList.stream().filter(
allCoupon -> canUseCouponUniqueList.stream().noneMatch(canUseCoupon -> Objects.equals(allCoupon.getId(), canUseCoupon.getId())))
.collect(Collectors.toList());

 

 

posted @ 2021-01-14 11:01  山阴路的秋天  阅读(389)  评论(0编辑  收藏  举报