Java Stream - 使用 toMap 将列表转换为地图

Java Stream - Convert List to Map using toMap

我是 stream() 的新手,正在考虑用 stream().

重构以下代码
public class User {
    private Integer id;
    private String name;
    private Date birthDate;
}

public class Post {
    private String content;
    private User user;
}

// I have a list of Users
List<User> users = new ArrayList<>();

// Goal is to initialize a Map of users -> List<Post>
Map<User, List<Post>> map = new HashMap<>();
for (User user : users) {
    map.put(user, new ArrayList<>());
}

我尝试了以下但没有成功。

Map<String, List<Post>> map = users.stream()
                .collect(Collectors.toMap(user, new ArrayList<>()));

关于如何使其正确的任何建议? 谢谢!

您的代码不起作用,因为您没有使用 lambda。您只是试图将对象传递给不起作用的 toMap 方法。

users.stream()
    // Function.identity/() is the same as writing u -> u.
    .collect(Collectors.toMap(Function.identity(), u -> new ArrayList<>()));