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

Java如何实现单key关联多类型值并按指定格式输出三列数据

实现方案

数据结构选型

直接使用 HashMap<String, CodeStat> 即可满足需求:

  • 外层Map的键为String类型的Code,与需求完全匹配
  • 自定义静态封装类CodeStat,同时存储Integer类型的用户计数、List<String>类型的用户名列表,类型安全无需强制转换,比用Map<Object, Object>存储多类型值的方案更易维护

完整实现代码

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// 原始的用户对象类(你已有的实现)
class UserItem {
    private String code;
    private String userName;

    public UserItem(String code, String userName) {
        this.code = code;
        this.userName = userName;
    }

    public String getCode() { return code; }
    public String getUserName() { return userName; }
}

// 自定义统计结果封装类
class CodeStat {
    private int userCount;
    private List<String> userNames;

    public CodeStat(String firstUserName) {
        this.userCount = 1;
        this.userNames = new ArrayList<>();
        this.userNames.add(firstUserName);
    }

    public void addUser(String userName) {
        this.userCount++;
        this.userNames.add(userName);
    }

    public int getUserCount() { return userCount; }
    public List<String> getUserNames() { return userNames; }
}

public class CodeStatDemo {
    public static void main(String[] args) {
        // 模拟你的原始对象列表
        List<UserItem> originalList = new ArrayList<>();
        originalList.add(new UserItem("Abc", "Jack"));
        originalList.add(new UserItem("Abc", "Mary"));
        originalList.add(new UserItem("Def", "Steven"));
        originalList.add(new UserItem("Ghi", "James"));
        originalList.add(new UserItem("Ghi", "Ray"));
        originalList.add(new UserItem("Ghi", "Jim"));

        // 统计逻辑
        Map<String, CodeStat> statMap = new HashMap<>();
        for (UserItem item : originalList) {
            String code = item.getCode();
            String userName = item.getUserName();
            if (statMap.containsKey(code)) {
                statMap.get(code).addUser(userName);
            } else {
                statMap.put(code, new CodeStat(userName));
            }
        }

        // 格式化输出
        System.out.printf("%-12s %-14s %s%n", "Code", "UserCount", "UserNames");
        for (Map.Entry<String, CodeStat> entry : statMap.entrySet()) {
            String code = entry.getKey();
            CodeStat stat = entry.getValue();
            String namesStr = String.join(", ", stat.getUserNames());
            System.out.printf("%-12s %-14d %s%n", code, stat.getUserCount(), namesStr);
        }
    }
}

输出结果

运行上述代码后会直接输出你要求的对齐格式:

Code        UserCount      UserNames
Abc         2              Jack, Mary
Def         1              Steven
Ghi         3              James, Ray, Jim

内容的提问来源于stack exchange,提问作者Divya Muruganantham

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:36:03