如何用Java从CSV文件提取同名行对应的所有颜色值列表
解决方案
你的代码存在几个关键问题,导致无法正确分组名称与对应颜色:
colourList仅初始化一次,所有自定义Object实例会共享同一个列表,最终所有条目都会包含所有颜色- 代码中
colourList.add(operation)是笔误,应为colourList.add(colour) Object<API> listings = new ArrayList<Object>()泛型声明错误,建议将自定义类重命名(避免和Java内置Object类冲突),比如改为Product,再修正声明为List<Product> listings = new ArrayList<>()
步骤1:修正自定义类
把你的Object类重命名为更清晰的名称(比如Product),保证封装性:
public class Product { private String name; private List<String> colours; public Product(String name, List<String> colours) { this.name = name; this.colours = new ArrayList<>(colours); // 传入列表副本,避免外部修改影响内部数据 } // 按需添加getter方法 public String getName() { return name; } public List<String> getColours() { return new ArrayList<>(colours); // 返回副本,保证内部数据不被外部篡改 } }
步骤2:用Map分组收集颜色
遍历CSV时,先通过Map按名称分组收集颜色,再转换为自定义类列表:
// 用try-with-resources自动关闭资源,避免内存泄漏 try (CSVReader reader = new CSVReader(new FileReader(new File(url.toURI()).getAbsolutePath()))) { reader.readNext(); // 跳过表头行 // 用Map分组:key为名称,value为该名称对应的所有颜色 Map<String, List<String>> nameColourMap = new HashMap<>(); String[] line; while ((line = reader.readNext()) != null) { String name = line[0].trim(); // 去除前后空格,避免因空格导致的分组错误 String colour = line[1].trim(); // 如果名称不在Map中,自动初始化空列表;然后添加当前颜色 nameColourMap.computeIfAbsent(name, k -> new ArrayList<>()) .add(colour); } // 将Map转换为自定义Product类的列表 List<Product> listings = new ArrayList<>(); for (Map.Entry<String, List<String>> entry : nameColourMap.entrySet()) { listings.add(new Product(entry.getKey(), entry.getValue())); } // 示例:获取'chair'对应的颜色列表 List<String> chairColours = nameColourMap.getOrDefault("chair", Collections.emptyList()); System.out.println(chairColours); // 输出格式类似[Blue, Green, Yellow] } catch (IOException | URISyntaxException e) { e.printStackTrace(); }
额外优化建议
- 如果需要去除重复颜色,可以将
ArrayList替换为LinkedHashSet(保留插入顺序),最后再转为列表:nameColourMap.computeIfAbsent(name, k -> new ArrayList<>(new LinkedHashSet<>())) .add(colour); - 确保CSV每行格式符合预期,第0列为名称、第1列为颜色,避免数组越界异常
内容的提问来源于stack exchange,提问作者Lemonand09
相关产品推荐
相关产品推荐

