I have a Java POJO with the following fields:
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 the database is stored in following data structure:
class ProductWithComments{
private String productName;
private String productCode;
private String price;
private String productId;
private String country;
private String comment;
private String languageCode;
}
As you can see, the product with comments has duplicate products., because each product has comments in many languages.
Using the Java Streams API, how can I convert the above list of data into List<ProductWithComments>
into List<Product>
.
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>
.
This question is similar to other questions in Stack Overflow, but my question is about multiple grouping fields. Other questions group by only one field. When group by is done using one field, it is straightforward.
You need to pull out a class to use as a key:
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())));