根据优惠券 id, 对优惠券进行分组
List<Coupon> userUsableCoupons = findCouponsByStatus(
userId, CouponStatus.USABLE.getCode()
);
// 通过模板 id , 获取可用优惠券
Map<Integer, List<Coupon>> templateId2Coupons = userUsableCoupons.stream()
.collect(Collectors.groupingBy(Coupon::getTemplateId));
自建分组类型进行分组
public enum ValueLevel{GGS,AGE,TTS}
Map<ValueLevel,List<Transaction>> map = transactions.stream().collect(Collectors.groupingBy(t -> {
if(t.getValue() <= 700) return ValueLevel.AGE;
else if (t.getValue() <=1000) return ValueLevel.GGS;
else return ValueLevel.TTS;
} ));
先分组再去重
Map<Integer,Set<Transaction>> map1 = transactions.stream().collect(groupingBy(Transaction::getYear,toSet()));
先分组,再计算每组的元素个数
Map<Integer,Long> map2 = transactions.stream().collect(groupingBy(Transaction::getYear,counting()));
每个子组内,交易额最大的
Map<Integer,Transaction> map3 = transactions.stream().collect(groupingBy(Transaction::getYear,collectingAndThen(maxBy(comparingInt(Transaction::getValue)),Optional::get)));
每个子组,取其交易额的总和
Map<Integer,Integer> map4 = transactions.stream().collect(groupingBy(Transaction::getYear,summingInt(Transaction::getValue)));
每个子组,进行另外条件筛选分层映射
Map<Integer,Set<ValueLevel>> map5 = transactions.stream().collect(groupingBy(Transaction::getYear,mapping( transaction -> {
if(transaction.getValue() <= 700) return ValueLevel.AGE;
else if(transaction.getValue() <= 1000) return ValueLevel.GGS;
else return ValueLevel.TTS;
},toCollection(HashSet::new))));