【问题标题】:Read text file line by line and store names into list in java逐行读取文本文件并将名称存储到java中的列表中
【发布时间】:2021-04-01 13:50:34
【问题描述】:

任务是读取给定文件并返回全名列表。我已经成功地分开了这些行,应该能够同时获得名字和姓氏,但我对如何做到这一点有点困惑。

我如何从readData() 获得全名?

我正在寻找的是这个输出 ["Alice Smith", "Bob Brown", "Carol White", "David Doe"] 而不是重复的名称。

到目前为止,我的代码如下所示:

public class GradeRepository {

    public GradeRepository(){
        readData();
    }
    public void readData() {

        for (String line : readLines()) {

            String[] parts = line.split("\\|");

            String firstName = parts[0];
            String lastName = parts[1];
            String subject = parts[2];
            String grade = parts[3];

            System.out.println(firstName);
            System.out.println(lastName);
            System.out.println(subject);
            System.out.println(grade);
            System.out.println(Arrays.toString(parts));
        }

    }

    public List<String> getFullNames() {
        List<String> fullNames = new ArrayList<>();

        return fullNames;
    }

    private List<String> readLines() {
        try {
            return Files.readAllLines(Paths.get("src/ex1/grades.txt"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

给定文本文件: 成绩.txt

Alice|Smith|math|5
Bob|Brown|english|4
David|Doe|math|3
Bob|Brown|math|4
Bob|Brown|chemistry|5
Alice|Smith|english|4
Carol|White|chemistry|3
David|Doe|chemistry|4

【问题讨论】:

  • 最好的办法是创建一个对象,可能是 Person,其字段包括 firstName、lastName 等。无论如何,如果您的目标是返回 firstName + lastName,您可以返回一个包含此信息的 Set
  • 创建一个集合。将每个名称放入集合中。

标签: java arraylist file.readalllines


【解决方案1】:

readData 需要修改为返回String[] 的列表,其中每个字符串数组代表一行或字段List&lt;String[]&gt; data 需要在GradeRepository 中创建并在readData 中填充。

接下来,要消除重复名称,应按照 cmets 中的建议使用 Set&lt;String&gt;,并且 LinkedHashSet 实现允许保持插入顺序。

readData 返回列表的示例实现:

public List<String[]> readData() {
    List<String[]> data = new ArrayList<>();
    for (String line : readLines()) {
        String[] parts = line.split("\\|");
        // ... print parts as above if necessary...
        data.add(parts);
    }
    return data;    
}

public Set<String> getFullNames() {
    Set<String> fullNames = new LinkedHashSet<>();

    for (String[] row : readData()) {
        fullNames.add(row[0] + " " + row[1]);
    }

    return fullNames;
}

最好使用 Stream API 来避免创建中间集合,因此所有这些方法都可以重写为一个:

public Set<String> getFullNames() throws Exception {
    return Files.lines(Path.of("dataset.txt")) // Stream<String>
        .map(line -> line.split("\\|")) // Stream<String[]>
        .filter(arr -> arr.length > 1) // ensure there are 2 columns at least
        .map(arr -> arr[0] + " " + arr[1]) // Stream<String>
        .collect(Collectors.toCollection(LinkedHashSet::new)); // get collection of unique names
}

【讨论】:

    猜你喜欢
    • 2017-07-14
    • 2021-06-03
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    相关资源
    最近更新 更多