我目前有一个 .txt 文件,我需要根据里面的内容读取和输出数据。我当前已打开文件并将文件中的每一行保存到 ArrayList 中。
.txt 文件的设置如下;
- 2380213012999 1508434343432 大卫死了
- 4327482397488 7439857934858 约翰活着
- 3857948998099 2222783749887 马丁杀死了凯莉
- 3857948998099 2222783749887 约翰杀死了大卫
当前代码;
{
try {
File file = new File("input.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
ArrayList<String> txtline = new ArrayList<String>();
while ((line = bufferedReader.readLine()) != null) {
txtline.add(line);
System.out.println(txtline);
}
fileReader.close();
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
我只是想知道是否有一种方法可以按第二个大数字对每行文本进行排序,我已经看过了,但似乎找不到任何东西。正确方向的一点或一些指导将是令人惊奇的,因为我目前很困惑,因为在我取得进一步进展之前我需要这样做。
最佳答案
您可以通过创建列表流来完成手头的任务,将 Comparator
对象传递给 sorted
方法来定义排序键 然后将其收集到 ArrayList
中。
数字比较:
txtline = txtline.stream()
.sorted(Comparator.comparingLong((String e) -> Long.parseLong(e.split(" ")[1])))
.collect(Collectors.toCollection(ArrayList::new));
按字符串比较:
txtline = txtline.stream()
.sorted(Comparator.comparing((String e) -> e.split(" ")[1]))
.collect(Collectors.toCollection(ArrayList::new));
关于java - 按字符串中的第二个单词对 ArrayList 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47318791/