gpt4 book ai didi

JAVA:如何按字母顺序对从文件读取并输出到控制台的字符串进行排序?

转载 作者:行者123 更新时间:2023-12-01 23:57:43 25 4
gpt4 key购买 nike

我想在控制台中按姓氏对从文件中读取的联系人进行排序?我该怎么做呢?联系人已写入从姓氏开始的文件中,当用户想要在控制台中查看联系人时,我只想按字母顺序将它们读回到应用程序中。

// Read from file, print to console. by XXXXX
// ----------------------------------------------------------
int counter = 0;
String line = null;

// Location of file to read
File file = new File("contactlist.csv");

try {

Scanner scanner = new Scanner(file);

while (scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
counter++;
}
scanner.close();
} catch (FileNotFoundException e) {

}
System.out.println("\n" + counter + " contacts in records.");

}
break;
// ----------------------------------------------------------
// End read file to console. by XXXX

最佳答案

在打印之前,将每一行添加到排序集中,如 TreeSet :

Set<String> lines = new TreeSet<>();
while (scanner.hasNextLine()) {
line = scanner.nextLine();
lines.add(line);
counter++;
}

for (String fileLine : lines) {
System.out.println(fileLine);
}

关于JAVA:如何按字母顺序对从文件读取并输出到控制台的字符串进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com