简体   繁体   English

Java 流 API - 按多个字段分组

[英]Java Streams API - Grouping by multiple fields

I have java POJO with following fields我有 java POJO,其中包含以下字段

class Product{
    private String productName;
    private String productCode;
    private String price;
    private String productId;
    private String country;
    private List<Comments> comments;
}

class Comments {
   private String productCode;
   private String languageCode;
   private String comment;

}

When I retrieve data from the database.当我从数据库中检索数据时。 I get the data in the following format.我得到以下格式的数据。

productName, productCode, price, productId, country, languageCode, comment

iPhone, 1XBA22, 1000, 134, USA, EN, comment in English

iPhone, 1XBA22, 1000, 134, USA, CN, comment in Chinese

laptop, 1234, 2000, 145, UK, EN, comment in English

laptop, 1234, 2000, 145, UK, CN, comment in Chinese

laptop, 1234, 2000, 145, UK, FR, comment in French

This result from db is stored in following data structure.来自 db 的结果存储在以下数据结构中。

class ProductWithComments{
    private String productName;
    private String productCode;
    private String price;
    private String productId;
    private String country;
    private String comment;
    private String languageCode;
}

now, as you can see, the product with comments has duplicate products.现在,如您所见,带有评论的产品有重复的产品。 because each product has comments in many languages, using Java Streams API, how can I convert the above list of data into List into List.因为每个产品都有多种语言的评论,使用Java Streams API,如何将上面的数据列表转换为List转换为List。

meaning, I group by Product and each product has many Comments.意思是,我按产品分组,每个产品都有很多评论。 So basically grouping by needs to happen using many columns (productName, productCode, price, productId, country) then all the Comments for one Group should be listed in List<Comments> .因此,基本上需要使用许多列(productName, productCode, price, productId, country)进行分组,然后一个 Group 的所有 Comments 都应该列在List<Comments>中。 Thanks in advance for any guide on this.提前感谢您对此的任何指导。

You need to pull out a class to use as a key:您需要拔出 class 用作钥匙:

class ProductKey {
  private String productName;
  private String productCode;
  private String price;
  private String productId;
  private String country;
  private String languageCode;
  // constructor, equals, hashCode, etc.
  // leave out the fields we're not grouping by
}

Then you just need to do:然后你只需要这样做:

products.stream().collect(
  Collectors.groupingBy(
    product -> new ProductKey(product.getProductName(), ...),
    Collectors.mapping(Product::getComment, Collectors.toList())));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM