最近在做一个项目,遇到了数据分类,和List数据分类合并处理逻辑(相同属性的去重,并把属性叠加起来),开发代码不容展示,写了一个demo方便大家理解:
新建一个实体类
@Data
public class OrderItem {
private String id;
private String goodsName;
private Integer goodsNuber;
public OrderItem(String id, String goodsName, Integer goodsNuber) {
this.id = id;
this.goodsName = goodsName;
this.goodsNuber = goodsNuber;
}
业务逻辑处理,以及注释:
public void goodsOrder() {
ArrayList orderList = new ArrayList<>();
orderList.add(new OrderItem("1", "苹果", 10));
orderList.add(new OrderItem("1", "苹果", 10));
orderList.add(new OrderItem("2", "香蕉", 12));
orderList.add(new OrderItem("2", "香蕉", 18));
orderList.add(new OrderItem("3", "丑橘", 26));
orderList.add(new OrderItem("3", "丑橘", 14));
orderList.add(new OrderItem("4", "火绒果", 27));
orderList.add(new OrderItem("4", "火绒果", 23));
//这个是java8中StreamAPI的分类方法,返回的是一个Map,
Map> collect = orderList.parallelStream().collect(Collectors.groupingBy(e -> (e.getId() + e.getGoodsName())));
System.out.println("StreamAPI的分类====>返回是一个Map:"+ collect);
//该Collector按分类顺序将所有输入元素收集到一个列表中,输出出来返回依然是Map collectList
Map> collecorsList = orderList.parallelStream().collect(Collectors.groupingBy(e -> (e.getId() + e.getGoodsName()),Collectors.toList()));
System.out.println("StreamAPI的分类顺序====>返回是一个Map:"+ collect);
//通过java8中StreamAPI分类方法处理后,然后通过List里面对象的属性值来去重List,并把相同属性的其他属性相加,得到一个新的List
ArrayList orderItemList = new ArrayList<>();
orderList.parallelStream().collect(Collectors.groupingBy(e -> (e.getId() + e.getGoodsName()),Collectors.toList())).forEach((id, transfer) -> {
transfer.stream().reduce((a, b) -> new OrderItem (a.getId(),a.getGoodsName(),a.getGoodsNuber()+b.getGoodsNuber())).ifPresent(orderItemList::add);
});
System.out.println("StreamAPI的分类相同属性的合并====>返回是新的List:"+ orderItemList);
}
控制台输出:
treamAPI的分类====>返回是一个Map:{3丑橘=[OrderItem(id=3, goodsName=丑橘, goodsNuber=26), OrderItem(id=3, goodsName=丑橘, goodsNuber=14)], 2香蕉=[OrderItem(id=2, goodsName=香蕉, goodsNuber=12), OrderItem(id=2, goodsName=香蕉, goodsNuber=18)], 1苹果=[OrderItem(id=1, goodsName=苹果, goodsNuber=10), OrderItem(id=1, goodsName=苹果, goodsNuber=10)], 4火绒果=[OrderItem(id=4, goodsName=火绒果, goodsNuber=27), OrderItem(id=4, goodsName=火绒果, goodsNuber=23)]} StreamAPI的分类顺序====>返回是一个Map:{3丑橘=[OrderItem(id=3, goodsName=丑橘, goodsNuber=26), OrderItem(id=3, goodsName=丑橘, goodsNuber=14)], 2香蕉=[OrderItem(id=2, goodsName=香蕉, goodsNuber=12), OrderItem(id=2, goodsName=香蕉, goodsNuber=18)], 1苹果=[OrderItem(id=1, goodsName=苹果, goodsNuber=10), OrderItem(id=1, goodsName=苹果, goodsNuber=10)], 4火绒果=[OrderItem(id=4, goodsName=火绒果, goodsNuber=27), OrderItem(id=4, goodsName=火绒果, goodsNuber=23)]} StreamAPI的分类相同属性的合并====>返回是新的List:[OrderItem(id=3, goodsName=丑橘, goodsNuber=40), OrderItem(id=2, goodsName=香蕉, goodsNuber=30), OrderItem(id=1, goodsName=苹果, goodsNuber=20), OrderItem(id=4, goodsName=火绒果, goodsNuber=50)]
具体的解析和注释,在代码块中,不理解的可以留言
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)