'How to convert Map value using stream

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?



Solution 1:[1]

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;
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1