The implementation of java~collection grouping groupby

For data aggregation, grouping operations are very common. There are lambda and linq in .net and lambda in java. Now let's implement grouping of a collection.

One preparation, there are two types

  @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;
  }

Second, create a set for two types and assign a value

    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")))));

Third, use lambda to group, mainly group the name field, and then store the result in a new set

    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));
    }

Four debug code, view grouped results at breakpoints

Next time, we will talk about a multi-field grouping, the current example is only for a single field.

Thanks for reading!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324782233&siteId=291194637