Implementation of java~ set grouping GroupBy

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.