如何用Java 8 Stream将Map列表转为角色对应姓名列表的Map
Hey there! Let's get this grouping done properly. You don't need that AbstractMap approach you mentioned—Java Streams have built-in collectors that make this super straightforward.
Here's the cleanest way to convert your List<Map<String, String>> into a Map<String, List<String>> grouped by role:
import java.util.List; import java.util.Map; import java.util.stream.Collectors; // Your sample data List<Map<String, String>> listOfData = List.of( Map.of("Role", "Batsman", "Name", "Player1"), Map.of("Role", "Batsman", "Name", "Player2"), Map.of("Role", "Bowler", "Name", "Player3") ); // The conversion logic Map<String, List<String>> roleToPlayers = listOfData.stream() .collect(Collectors.groupingBy( // Define the grouping key: extract the "Role" value from each map entry entry -> entry.get("Role"), // For each group, extract "Name" values and collect them into a List Collectors.mapping(entry -> entry.get("Name"), Collectors.toList()) ));
How this works:
Collectors.groupingBy()handles the core grouping logic with two key parts:- A function that returns the grouping key (we pull the "Role" value from each entry in the list)
- A downstream collector that processes elements in each group.
Collectors.mapping()extracts the "Name" value from each map, andCollectors.toList()gathers those names into a list for the role.
Optional: Handle missing keys
If there's a chance some maps might not have "Role" or "Name" keys, use getOrDefault() to avoid NullPointerException and assign safe defaults:
Map<String, List<String>> roleToPlayers = listOfData.stream() .collect(Collectors.groupingBy( entry -> entry.getOrDefault("Role", "Unknown"), Collectors.mapping(entry -> entry.getOrDefault("Name", "Unnamed Player"), Collectors.toList()) ));
When you run this, roleToPlayers.get("Batsman") will give you [Player1, Player2], and roleToPlayers.get("Bowler") will return [Player3]—exactly what you need!
内容的提问来源于stack exchange,提问作者user1692342
相关产品推荐
相关产品推荐

