Java 如何按每行中的值对存储在文本文件中的条目进行排序
我有一个包含一些数据、数字和分数的文本文件,我需要按高分(10,9,8,7,6…)对这些数据进行排序 我怎么做 也许通过读取并创建ArrayList?还是分开 我不知道怎么做 我需要按分数(2,2,1,0.8,…)对文本进行排序Java 如何按每行中的值对存储在文本文件中的条目进行排序,java,sorting,user-interface,Java,Sorting,User Interface,我有一个包含一些数据、数字和分数的文本文件,我需要按高分(10,9,8,7,6…)对这些数据进行排序 我怎么做 也许通过读取并创建ArrayList?还是分开 我不知道怎么做 我需要按分数(2,2,1,0.8,…)对文本进行排序 我试着用扫描仪进行扫描,但不起作用不清楚您需要输出什么,但您基本上有以下步骤: 逐行读取文件。您可以使用BufferedReader,或者更现代的Java8方法,通过获取字符串的流,每个字符串代表一行 streamlines=Files.lines(path.get(
我试着用扫描仪进行扫描,但不起作用不清楚您需要输出什么,但您基本上有以下步骤:
BufferedReader
,或者更现代的Java8方法,通过获取字符串的流
,每个字符串代表一行
streamlines=Files.lines(path.get(fileName))代码>
分数:
,将8添加到其中,并从中获取字符串的子字符串,这将是您的分数,您可以将其转换为整数。获得数据后,只需使用集合或流提供的排序机制之一对其进行排序
列出分数=行
.map(line->line.substring(line.indexOf(“分数”)+8))
.map(Double::parseDouble)
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList())代码>
Bogdan,2,2x2,2
Leo,6,2x2,0.6667
因此,如果您可以修改粘贴在问题中的函数,以这种格式输出它,对您来说会容易得多,因为您只需使用String.split(“,”)
。否则,您必须使用indexOf()
和substring()
找到每个数据项所在的位置并将其提取出来。那是你的锻炼
public class Player {
private final String name;
private final int time;
private final String grid;
private final double score;
public Player(String name, int time, String grid, double score) {
this.name = name;
this.time = time;
this.grid = grid;
this.score = score;
}
public double getScore() {
return score;
}
// todo: put all the getters
public static Player parse(String line) {
//todo: extract the data items from the string...
}
@Override
public String toString() {
return String.format("%s (Time: %d Grid: %s) Score: %.4f", name, time, grid, score);
}
}
然后,您的流处理变得更简单:
列出分数=行
.map(播放器::解析)
.sorted(Comparator.comparingDouble(Player::getScore).reversed())
.collect(Collectors.toList())代码>您是否关心文本中的其余信息,还是只想要数字?是否只想按降序对数字进行排序?@VinitMehta仅在descending@jbx文本必须是,但它应该按最后一个数字排序。首先,您必须反转每个字符串,然后用:拆分,以便获得数字,然后使用一些排序算法。
public class Player {
private final String name;
private final int time;
private final String grid;
private final double score;
public Player(String name, int time, String grid, double score) {
this.name = name;
this.time = time;
this.grid = grid;
this.score = score;
}
public double getScore() {
return score;
}
// todo: put all the getters
public static Player parse(String line) {
//todo: extract the data items from the string...
}
@Override
public String toString() {
return String.format("%s (Time: %d Grid: %s) Score: %.4f", name, time, grid, score);
}
}