Search code examples
javacollectionsjava-8hashmapjava-stream

How to filter two maps and make third map by using Lambda expression java 8


Map<String,String> persons = new HashMap<>();
persons.put("aaaa@testing","123456789");
persons.put("bbbb@testing","987654321");

Map<String,UsersDTO> users = new HashMap<>();
users.put("aaaa@testing", UsersDTO1);
users.put("bbbb@testing",UsersDTO2);

//Below one is the my required final map by using above two maps by using java 8 Lambdas
Map<String,UsersDTO> finalMap = new HashMap<>();
finalMap.put("123456789",UsersDTO1);
finalMap.put("987654321",UsersDTO2);

How to make finalMap by using the two maps above? This type of question might be there but I want to give special focus on this so that's why I am posting it. How to make by using the lambda expressions?


Solution

  • You could do that but note that you will get a Map<String,UserDto>:

    Map<String,UsersDTO> finalMap =
            persons.entrySet().stream()
                    .collect(Collectors.toMap(Map.Entry::getValue, e-> users.get(e.getKey())));
    

    As suggested by Andreas, if the email doesn't have a match between the two maps, you could handle that case. For example by ignoring the entry :

    Map<String, UsersDTO> finalMap =
            persons.entrySet().stream()
                    .filter(e -> users.containsKey(e.getKey()))
                    .collect(Collectors.toMap(Map.Entry::getValue, e -> users.get(e.getKey())));