2

I have object Product, Client and ProductModel as below In the main function, I am trying to create a map , with key as client name and values would be list of productModel

@Getter
@Setter
@AllArgsConstructor
class Client{
    String name;
    String location;
}

@Getter
@Setter
@AllArgsConstructor
class Product {
    String name;
    String value;
    String rating;
    Client client;
}

public class Test {
    public static void main(String[] args) {

    Client c1 = new Client("abc", "ldn");
Client c2 = new Client("lmn","nyc");
Client c3 = new Client("abc","eur");
Client c4 = new Client("xyz","ldn");

 Arrays.asList(new Product("tshirt", "v1", "4",c1),
               new Product("shoes", "v2","3",c2), 
               new Product("dress", "v3","2",c3), 
               new Product("belt", "v4","4",c4)
   .stream();

After this, how to create a map, where key is the client name and value is list of ShopModel

@Getter
@Setter
@AllArgsConstructor
class ProductModel{
    String productName; // maps to name in Product
    String prouductValue; // maps to value in Product
    String location;// maps to location in client
}

The final map output should look as below

Key Value
abc {tshirt, v1, ldn},
    {dress,  v3, eur}
lmn {shoes, v2, nyc}
xyz {belt, v4, ldn}
 
1
  • Instead of Arrays.asList(...).stream() you can do that in one step: Arrays.stream(...) Commented Aug 3, 2021 at 11:37

1 Answer 1

3

below code may help

 final Map<String, List<ProductModel>> collect = Arrays.asList(new Product("tshirt", "v1", "4", c1),
                new Product("shoes", "v2", "3", c2),
                new Product("dress", "v3", "2", c3),
                new Product("belt", "v4", "4", c4))
                .stream()
                .collect(Collectors.groupingBy(e -> e.getClient().getName(),
                        Collectors.mapping(e -> new ProductModel(e.getName(), e.getValue(), e.getClient().getLocation()),
                                Collectors.toList())
                ));

helpful link -> https://www.baeldung.com/java-groupingby-collector

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.