1

I'm having a list data from database. Now, i need to make a json array that each object is a group of data and having the same created date.

Is there any way to do this as simple as posible?.

Example:

Product entity:

class Product {
 private Long id;
 private String name;
 private Date createdDate;
}

Data after get from database:

List<Product> products = new ArrayList<Product>();
products = daoProduct.getProducts();

for(Product product : products){
   logger.info("{} : {} - {}", product.id, product.name, product.createdDate)
}

  • result:
  1 : bread - 10-Jun-2019
  2 : apple - 11-April-2019
  3 : banana - 12-July-2019
  4 : milk - 10-Jun-2019
  5 : cocacola - 11-April-2019
  6 : pepsi - 12-July-2019
  7 : coffee - 10-Jun-2019

Expected: I want to make a response object with data like this

class ProductRest{
 private Date createdDate;
 private int count;
 private List<Product> listProduct;
}

and the response will be like this

[
 {
  "createdDate":"10-Jun-2019",
  "count":3
  "listProduct":[
     {"id":1,"name":"bread","createdDate":"10-Jun-2019"},
     {"id":4,"name":"milk ","createdDate":"10-Jun-2019"}  ,
     {"id":7,"name":"coffee ","createdDate":"10-Jun-2019"}            
   ]
 },
 {
  "createdDate":"11-April-2019",
  "count":2
  "listProduct":[
     {"id":2,"name":"apple","createdDate":"11-April-2019"},
     {"id":5,"name":"cocacola","createdDate":"11-April-2019"}           
   ]
 },
 {
  "createdDate":"12-July-2019",
  "count":2
  "listProduct":[
     {"id":3,"name":"banana","createdDate":"12-July-2019"},
     {"id":6,"name":"pepsi","createdDate":"12-July-2019"}           
   ]
 } 
]

Please help me do the java coding step to make expected result. Thanks!

Tuan Anh
  • 15
  • 5

1 Answers1

0

Iterate teh product list and add to HashMap. Then print that response.

Ref: Group a list of objects by an attribute : Java

Senthil
  • 2,156
  • 1
  • 14
  • 19