What is the result of following code execution:

class User {
    public Integer id;
    public String username;
    
    public User(Integer id, String username) {
        this.id = id;
        this.username = username;
    }
}

public static void main (String[] args) {
    List<User> userList = new ArrayList<>();
    userList.add(new User(1, "admin"));
    userList.add(new User(2, "guest"));
    userList.add(new User(3, null));

    Map<Integer, String> idsUsernamesMap = 
        userList.stream().collect(Collectors.toMap(user -> user.id, user -> user.username));
                
    idsUsernamesMap.forEach( (k,v) -> System.out.println("id: " + k + "; username: " + v));
}
Explanation
Collectors.toMap is based on Map.merge, which throws NullPointerException if the specified key is null and this map does not support null keys or the value or remappingFunction (the function to recompute a value if present)is null.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести