1

I have a List<Emp> where Emp is name, id, address.

value saved is like

("Name1, 11, Delhi"),
("Name1, 12, Chennai"),
("Name2, 13, Delhi"),
("Name3, 14, Delhi"),
("Name4, 15, Delhi")

I am trying to create a Map with Key as Name and value as list of Emp which has those name.

This is what I tried, and it's working fine, but I am looking for a better way.

Map<String, List<Emp>> nameMap = new HashMap<>();
  empList.forEach(
                empDto -> {
                    List<EmpDto> empDtoName = new ArrayList<>();
                    String name = empDto.getName();
                    if (nameMap .containsKey(name))
                    {
                        empDtoName = nameMap.get(name);
                    }
                    empDtoName.add(userRoleDto);
                    userRoleMap.put(usrNwId, empDtoName);
                }
        );
Eran
  • 387,369
  • 54
  • 702
  • 768

1 Answers1

2

Use a Stream and collect its elements with a groupingBy collector:

Map<String, List<Emp>> nameMap =
    empList.stream() 
           .collect(Collectors.groupingBy(Emp::getName));
Eran
  • 387,369
  • 54
  • 702
  • 768