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

Srikanth Janapati :
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 above two maps? this type of questions 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?

davidxxx :

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())));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307872&siteId=1