You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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:
    1. A function that returns the grouping key (we pull the "Role" value from each entry in the list)
    2. A downstream collector that processes elements in each group. Collectors.mapping() extracts the "Name" value from each map, and Collectors.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:27:42