微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在java中逐行读取文本文件并将名称存储到列表中

如何解决在java中逐行读取文本文件并将名称存储到列表中

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

如何从 regex = r"D.*cube" for row in range(len(df)): for col in range(len(df.columns)): if df.iloc[row,col] == regex: #treatment... ............. 获取全名?

我正在寻找的是这个输出 readData() 而不是重复的名称

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

["Alice Smith","Bob brown","Carol White","David Doe"]

给定的文本文件: 成绩.txt

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);
        }
    }
}

解决方法

readData 需要修改以返回 String[] 的列表,其中每个字符串数组代表一行,或者需要在 List<String[]> data 中创建并填充字段 GradeRepositoryreadData

接下来,要去除重复名称,应按照注释中的建议使用 Set<String>,并且 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
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。