Java中拆分数组元素存入ArrayList并实现CSV姓名拆分
解决方案
1. 修正现有代码的语法与逻辑问题
你的代码存在几个明显问题:
- 字符串拆分时的转义错误:
split(";\\")和split(",\\")是无效语法,应改为split(";")和split(","); - 集合添加逻辑错误:
Collections.addAll(authorNames, authors)会把authors数组的每个字符串单独加入列表,而非将整个数组作为一个元素添加,应改用authorNames.add(authors); - 缺少姓名拆分的核心逻辑。
2. 完整实现代码
以下是符合需求的完整代码,包含姓名拆分逻辑,并将结果存储为 Author 对象列表:
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class Author { private String name; private String surname; public Author(String name, String surname) { this.name = name; this.surname = surname; } public String getName() { return name; } public String getSurname() { return surname; } @Override public String toString() { return "{name=" + name + ", surname=" + surname + '}'; } // 解析单个作者姓名,按规则拆分名字和姓氏 private static Author parseAuthorName(String fullName) { // 去除姓名前后的空格 fullName = fullName.trim(); if (fullName.isEmpty()) { return new Author("", ""); } // 按空格拆分(处理多个连续空格的情况) String[] nameParts = fullName.split("\\s+"); if (nameParts.length == 1) { // 只有一个部分,姓氏为该部分,名字为空 return new Author("", nameParts[0]); } // 最后一部分是姓氏,其余部分拼接为名字 StringBuilder firstNameBuilder = new StringBuilder(); for (int i = 0; i < nameParts.length - 1; i++) { if (i > 0) { firstNameBuilder.append(" "); } firstNameBuilder.append(nameParts[i]); } return new Author(firstNameBuilder.toString(), nameParts[nameParts.length - 1]); } public void listAllNames() { String path = "C:\\Users\\ahmex\\Desktop\\publications.shortened.csv"; String currentLine = ""; // 存储所有作者对象 ArrayList<Author> allAuthors = new ArrayList<>(); try (BufferedReader fileReader = new BufferedReader(new FileReader(path))) { // 跳过表头行 fileReader.readLine(); while ((currentLine = fileReader.readLine()) != null) { String[] line = currentLine.split(";"); if (line.length < 2) { // 跳过格式错误的行 continue; } String[] authors = line[1].split(","); // 遍历每个作者姓名,解析后加入列表 for (String authorName : authors) { allAuthors.add(parseAuthorName(authorName)); } } System.out.println("所有作者信息:"); for (Author author : allAuthors) { System.out.println(author); } System.out.println("作者总数:" + allAuthors.size()); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new Author("", "").listAllNames(); } }
3. 关键逻辑说明
- 姓名拆分规则:通过
parseAuthorName方法实现,先去除姓名前后空格,再按空格拆分字符串;最后一部分作为姓氏,其余部分拼接为名字; - 资源自动关闭:使用
try-with-resources语法自动关闭BufferedReader,避免资源泄漏; - 异常处理:跳过格式错误的行,避免因CSV行格式问题导致程序崩溃;
- 跳过表头:直接读取第一行后跳过,替代原代码中
authorNames.remove(0)的写法,更直观。
内容的提问来源于stack exchange,提问作者the25thbaam4
相关产品推荐
相关产品推荐

