Krishan
Krishan

Reputation: 1443

How to create a map, with list of custom object as value, from a list using java 8 streams?

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}
 

Upvotes: 2

Views: 1894

Answers (1)

divilipir
divilipir

Reputation: 960

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

Upvotes: 3

Related Questions