我正在尝试显示 txt 文件中的元素列表,然后根据每条记录的日期对列表进行排序。我已经使用哈希集来完全加载 txt 文件并且可以正常工作。
主要问题是我似乎找不到一种方法来根据每条记录下包含的日期对 txt 文件和每条记录进行排序。
btnPrintList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// File path & name
Path path = Paths.get(System.getProperty("user.dir")).resolve("vehicle.txt");
try {
BufferedReader reader = new BufferedReader(new
FileReader(path.toFile()));
Set<String> carsPrint = new HashSet<>();
String line = reader.readLine();
while (line != null) {
System.out.println("processing line: " + line);
if (line.trim().contains("-")) {
String[] words = line.split("");
}
if (!line.trim().equals("")) {
String[] words = line.split("");
}
line = reader.readLine();
}
}
catch (IOException e1) {
block
e1.printStackTrace();
}
}
});
这里是引用的文本文件
a, Honda Jazz, Hatchback, grey, 20000, none, manual, 8000, 2018-09-01, 2018-10-04,
b, Mercedes Citan, Van, small, white, 35000, front damage, manual, 9500, 2018-11-04,
c, Ford Transit, Van, small, black, 60000, none, automatic, 7300, 2018-11-01,
d, Lexus IS, Saloon, white, 23000, indent on passenger door, automatic, 18100, 2019-01-02,
e, Lexus IS, Saloon, dark blue, 6000, none, manual, 26100, 2018-10-04, 2018-10-14,
f, Mercedes Citan, Van, small, white, 35900, front windscreen damage, automatic, 10000, 2018-08-04,
g, Lexus NX, SUV, dark blue, 12000, none, automatic, 31000,
h, Ford SMax, MPV, red, 70000, none, manual, 11000, 2017-01-13,
i, Vauxhall Movano, Van, large, white, 60000, rear windscreen damage, manual, 5000, 2019-01-10, 2019-03-01,
j, Vauxhall Insignia, Saloon, green, 45000, none, automatic, 10800, 2018-08-10, 2019-03-05,
k, Vauxhall Insignia, Saloon, red, 40000, none, manual, 10200, 2018-08-10,
l, Vauxhall Movano, Van, large, silver, 60000, none, automatic, 8800,
m, BMW 3, Saloon, black, 49000, door damage, manual, 9500, 2019-03-01, 2019-03-05,
n, Ford SMax, MPV, red, 70000, none, automatic, 3800,
o, Mercedes EClass, Coupe, yellow, 25000, none, automatic, 10400, 2018-03-08, 2019-03-02,
p, Jaguar FType, Coupe, silver, 3000, none, automatic, 52000, 2018-03-01,
最佳答案
根据定义,hashset结构是不能排序的。它不保证集合的迭代顺序;特别是,它不保证顺序会随着时间的推移保持不变。 (来自Documentation)
但您可以改用 ArrayList:
List<?> sortedCarsPrint = new ArrayList<>(carsPrint);
sortedCarsPrint.sort((o1,o2) -> o1.getDateTime().compareTo(o2.getDateTime()));
关于java - 如何检索文本文件中的特定字符串并根据字符串中的元素进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55759013/