我有一个包含多个属性的用户定义对象。因为它们都具有与 String
相同的数据类型,我想使用 Streams 将所有这些属性值收集到 Map
中。我不知道Collectors.toMap()
或Collectors.groupingBy()
能够提供此服务。
public class TeamMates{
private String playerFirstName;
private String playerLastName;
private String playerMaidenName;
//Constructors , getters and Setters
}
我有一个List<TeamMates>
我想用它来流式传输并将其收集到 Map<String,List<String>>
的对象.
我希望 map 包含
(playerFirstName,("John","Bob"));
(playerLastName,("Joe","Henry"));
(playerMaidenName,("H","K"));
因为我不想多次使用流式传输来单独收集每个属性或使用 forEach
,有什么办法可以通过单个流获取上述属性。
最佳答案
首先创建值生成 getter 方法及其各自字段名称的映射。
// Map.of is available from Java 9.
// If you are using java 8 you could create the below using a normal HashMap.
Map<String, Function<TeamMates, String>> mapper
= Map.of("playerFirstName", TeamMates::getPlayerFirstName,
"playerLastName", TeamMates::getPlayerLastName,
"playerMaidenName", TeamMates::getPlayerMaidenName);
现在迭代此映射器函数并将每个映射应用到队友列表
// applies getter method on each teammate object and returns the list of strings.
Function<Function<TeamMates, String>, List<String>> listMapper
= fn -> list.stream().map(fn::apply).collect(Collectors.toList());
// assume static import of Collectors.toMap
Map<String, List<String>> map = mapper.entrySet().stream()
.collect(toMap(Entry::getKey,
e -> listMapper.apply(e.getValue())));
我还建议将您的类命名为 TeamMate
而不是 TeamMates
,因为该类代表单个团队伙伴实体。
关于java - 使用单个 Stream 将多个属性收集到 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68968773/