[英]JAVA: How to sort strings read from file and output to console in alphabetical order?
I'm looking to sort the contacts read from a file in alphabetical order by last name to the console? 我正在寻找按姓氏顺序按字母顺序对从文件中读取的联系人进行排序? How would I go about doing so?
我将如何去做? The contacts are already written to file starting with the last name, I just want to read them back into the application in alphabetical order when a user wants to view the contacts in the console.
联系人已经以姓氏开头写入文件,当用户想要在控制台中查看联系人时,我只想按字母顺序将它们读回到应用程序中。
// 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
package main.java.com.example;
import java.io.*;
import java.net.URL;
import java.util.Set;
import java.util.TreeSet;
public class ReadFromCSV {
public static void main(String[] args) {
try {
final ClassLoader loader = ReadFromCSV.class.getClassLoader();
URL url = loader.getResource("csv/contacts.csv");
if (null != url) {
File f = new File(url.getPath());
BufferedReader br = new BufferedReader(new FileReader(f));
Set<String> set = new TreeSet<String>();
String str;
while ((str = br.readLine()) != null) {
set.add(str);
}
for (String key : set) {
System.out.println(key);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
从文件中读取名称,并将其放入SortedSet类的对象中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.