java~集合分組groupby的實現

來源:互聯網
上載者:User

標籤:資料   lam   現在   rod   分享   count   name   groupby   準備工作   

對於資料彙總來說,分組操作是很常見的,在.net裡有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().collect(Collectors.groupingBy(Product::getName));    products = new ArrayList<>();    for (Map.Entry<String, List<Product>> str : groupByPriceMap.entrySet()) {      List<Item> items = new ArrayList<>();      for (Product product : str.getValue()) {        items.addAll(product.getItems());      }      products.add(new Product(str.getKey(), "", items));    }

四 調試代碼,在斷點處查看分組後的結果

下次,我們將講一個多欄位的分組,目前的例子只是針對單個欄位來說的。

感謝閱讀!

java~集合分組groupby的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.