java~集合分组groupby的实现
对于数据聚合来说,分组操作是很常见的,在⾥有lambda和linq,⽽在java⾥也有lambda,现在我们来实现对⼀个集合进⾏分组。⼀准备⼯作,有两个类型
@Value
class Item {
private Date createAt;
private int count;
private BigDecimal price;
}
@Value
class Product {
private String name;
private String code;
private List<Item> items;
}
⼆为两个类型建⽴集合,并赋值
List<Product> products = new ArrayList<>();
products.add(new Product("apple", "1001", Arrays.asList(
new Item(new Date(2018, 1, 1), 10, new BigDecimal("9.99")))));
products.add(new Product("apple", "1001", Arrays.asList(
new Item(new Date(2018, 2, 1), 10, new BigDecimal("19.99")))));
products.add(new Product("apple", "1001", Arrays.asList(
new Item(new Date(2018, 3, 1), 10, new BigDecimal("29.99")))));
三使⽤lambda进⾏分组,主要对name字段进⾏分组,然后把结果存在⼀个新的集合⾥
Map<String, List<Product>> groupByPriceMap =
products.stream().upingBy(Product::getName));
products = new ArrayList<>();
for (Map.Entry<String, List<Product>> str : Set()) {
List<Item> items = new ArrayList<>();
for (Product product : Value()) {
groupby分组
items.Items());
}
products.add(new Key(), "", items));
}
四调试代码,在断点处查看分组后的结果
五多条件分组的实现
Function<Product, List<Object>> compositeKey = personRecord ->
Arrays.Name(), Code());
Map<Object, List<Product>> map =
products.stream().upingBy(compositeKey));
感谢阅读!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。