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
相关产品推荐
相关产品推荐

