Map要映射的对象列表

时间:2018-01-17 11:02:11

标签: java java-8 grouping java-stream

我想使用Java Streams按id()分组用户列表。

例如,我有List: new User(1L, "First"), new User(2L, "Second")

如何将此列表分组以获取Map<Long, User>

1L -> new User(1L, "First"),
2L -> new User(2L, "Second")

User.java

public final class User {
    final Long id;
    final String name;

    public User(final Long id, final String name) {
        this.id = id;
        this.name = name;
    }

    public Long id() {
        return this.id;
    }

    public String name() {
        return this.name;
    }
}

1 个答案:

答案 0 :(得分:2)

如果每个ID都映射到一个User,请使用Collectors.toMap

Map<Long,User> users = list.stream().collect(Collectors.toMap(User::id,Function.identity()));