How to convert Map value using stream

Viewed 144

I have a task: Return a map of companies, where the key is its name and the value is a list of employees stored as String consisting of firstName and lastName separated by space. Here is my solution and its works fine:

    Map<String, List<String>> getUserPerCompanyAsString() {
        return getCompanyStream()
                .collect(Collectors.toMap(Company::getName, company ->  getUserNames(company.getUsers())));
    }

    private List<String> getUserNames(List<User> users) {
        return users.stream()
                .map(user -> user.getFirstName() + " " + user.getLastName())
                .collect(Collectors.toList());
    }

public class Company {
    private final String name;
    private final List<User> users;
}

public class User {
    private final String firstName;
    private final String lastName;
    private final Sex sex;
    private final int age;
    private final List<Account> accounts;
    private final List<Permit> permits;
}

So my question, how to convert List<User> as map value to List<String> with firstName and lastName separated by space in one stream chain without helper method?

2 Answers

Solution

Thanks to Thomas suggestion I'm able solve this problem without helper method:

    Map<String, List<String>> getUserPerCompanyAsString() {
        return getCompanyStream()
                .collect(Collectors.toMap(Company::getName, company -> company.getUsers().stream()
                                .map(user -> user.getFirstName() + " " + user.getLastName())
                                .collect(Collectors.toList())));

I get that you want to get ride of the helper method. A cleaner way would be to include the getUserNames method inside of Company, it makes more sense than to have this logic hanging inside of a Collector.

The solution would also be more readable

Map<String, List<String>> getUserPerCompanyAsString() {
    return getCompanyStream().collect(
        Collectors.toMap(
            Company::getName,
            Company::getUserNames
        )
    );
}



public class Company {
    private final String name;
    private final List<User> users;

    // Constructor making sure users is not null

    private List<String> getUserNames() {
        return this.users
                   .stream()
                   .map(User::getFullName)
                   .collect(Collectors.toList());
    }
}

public class User {
    private final String firstName;
    private final String lastName;
    
    // Etc.

    public String getFullName() {
        return firstName + " " + lastName;
    }
}
Related