For data aggregation, grouping operations are common, with Lambda and LINQ in. NET, and Lambda in Java, and now we're going to implement grouping a collection.
A preparatory work, there are two types of
@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; }
Two sets are set for two types and are assigned a value
list<product> products =NewArraylist<>(); Products.add (NewProduct ("Apple", "1001", Arrays.aslist (NewItem (NewDate (2018, 1, 1), 10,NewBigDecimal ("9.99"))))); Products.add (NewProduct ("Apple", "1001", Arrays.aslist (NewItem (NewDate (2018, 2, 1), 10,NewBigDecimal ("19.99"))))); Products.add (NewProduct ("Apple", "1001", Arrays.aslist (NewItem (NewDate (2018, 3, 1), 10,NewBigDecimal ("29.99"))));
Three use lambda to group, mainly group the Name field, and then present the result in a new collection
map<string, list<product>> groupbypricemap = products.stream (). Collect (Collectors.groupingby ( Product::getname)); New Arraylist<>(); for (map.entry<string, list<product>> str:groupByPriceMap.entrySet ()) { ListNew Arraylist<>(); for (Product product:str.getValue ()) { Items.addall (Product.getitems ()); } Products.add (new Product (Str.getkey (), "", items));
Quad Debug Code, view grouped results at breakpoints
Next time, we're going to talk about a multi-field grouping, and the current example is just a single word.
Thanks for reading!
Implementation of java~ set grouping GroupBy