Home > OS >  How to map a Map into another Map using Java Stream?
How to map a Map into another Map using Java Stream?

Time:03-18

I'm learning Java with Stream and I have this Map<String, List<Customer>> map1 and I want to map it into this Map<String, List<CustomerObj>> map2. How can I do this especially using Java Stream? Any feedback will be apreciated!

CodePudding user response:

You can stream the entries of map1 and collect with Collectors.toMap, using key mapper Map.Entry::getKey. For the value mapper you can get the entry value list, then stream and map from Customer to CustomerObj, and finally collect to List.

Here's and example using Integer instead of Customer and String instead of CustomerObj:

Map<String, List<Integer>> map1 = Map.of(
        "A", List.of(1, 2), 
        "B", List.of(3, 4), 
        "C", List.of(5, 6));
    
Map<String, List<String>> map2 = map1.entrySet().stream().collect(
        Collectors.toMap(Map.Entry::getKey, 
                entry -> entry.getValue().stream()
                        .map(String::valueOf).toList()));

CodePudding user response:

Please refer to this link https://www.baeldung.com/java-merge-maps, it will help you.

CodePudding user response:

You may do it like so:

Customer c1 = new Customer("İsmail", "Y.");
Customer c2 = new Customer("Elvis", "?.");
        
Map<String, List<Customer>> customerList = new HashMap<>();
customerList.put("U1", Arrays.asList(c1));
customerList.put("U2", Arrays.asList(c1, c2));
        
Map<String, List<CustomerObj>> customerObjList = customerList
        .entrySet().stream().collect(
                Collectors.toMap(Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .map(CustomerObj::new)
                                // or .map(c -> new CustomerObj(c))
                                .collect(Collectors.toList())
                )
        );
    }
private static class Customer {

    private String firstName;
    private String lastName;

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

private static class CustomerObj {

    private String fullName;

    public CustomerObj(Customer customer) {
        this.fullName = String.join(" ",
                customer.getFirstName(), customer.getLastName()
        );
    }

    public String getFullName() {
        return fullName;
    }
}

@Oboe's answer works in Java 16 and this answer is similar to your models and easier to understand.

  • Related