Search code examples
java-8streamhashmapflatmapcollect

Convert list of Object to Map<Key, List<Object>> with java 8 stream


So I have a list of users with several information including company uid, this value can be found in several users, as it defines to what company the user belongs to. I need to create a Map of userList where the map key is company uid. I have managed to do so using this code:

HashMap<String, List<LDAPUser>> allUsers = new HashMap<>();
    userService.findAllUsers().forEach(u -> {
        Optional.ofNullable(allUsers.putIfAbsent(u.getCompanyUid(),
                new ArrayList<>(Collections.singletonList(u))))
                .ifPresent(list -> list.add(u));
    });

Even if it works fine, I think there must be a cleaner approach using flatMap, map or collect method from stream, but I can't get it to work basically because I don't see how I can create a list containing all users.


Solution

  • There's a collector to group things, consider the following example

    Application.java

    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class Application {
    
        private static class User {
    
            private final String name;
    
            private final Integer companyId;
    
            public User(String name, Integer companyId) {
                this.name = name;
                this.companyId = companyId;
            }
    
            public String getName() {
                return name;
            }
    
            public Integer getCompanyId() {
                return companyId;
            }
    
            @Override
            public String toString() {
                return "User{" +
                        "name='" + name + '\'' +
                        ", companyId=" + companyId +
                        '}';
            }
        }
    
        public static void main(String[] args) {
            final List<User> users = Arrays.asList(new User("A", 1), new User("B", 1), new User("C", 2));
            final Map<Integer, List<User>> byCompanyId = users.stream()
                    .collect(Collectors.groupingBy(User::getCompanyId));
            System.out.println(byCompanyId);
        }
    }
    

    that will print

    {1=[User{name='A', companyId=1}, User{name='B', companyId=1}], 2=[User{name='C', companyId=2}]}