在我的文本文件中,“ D:\ Leaderboard.txt”中有很多行,其中用户名(例如“ Username123”)和乐谱(例如“ 12”)以“ Username123,12“。如何获取这些值,将其转换为二维数组,执行插入排序,以使这些值按分数顺序排序,然后在第5位后将其切断,并将前5个分数按顺序排列到文本中文件?非常感谢所有帮助。
您的要求很难做到。
public static void main(String [] args) {
List<Item> items = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("D:\Leaderboard.txt"))) {
String line = reader.readLine();
while (line != null) {
String [] arr= line.split("\\s");
Item item = new Item(arr[0], Integer.valueOf(arr[1]));
items.add(item);
line = reader.readLine();
}
} catch (Exception e) {
e.printStackTrace();
}
Collections.sort(items);
System.out.println(items.get(4).getName());
}
private static class Item implements Comparable<Item>{
private String name;
private Integer score;
public Item(String name, Integer score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
@Override
public int compareTo(Item o) {
return score.compareTo(o.score);
}
}
这里是如何使用HashMap和流api对它进行排序的方法。
public static void main(String[] args)
{
//first read in the data
Map<String, Integer> users = new HashMap<>();
try
{
BufferedReader br = new BufferedReader(new FileReader("text.txt"));
String line;
//read the line
line = br.readLine();
while(line!=null)
{
//split the line on the comma
String[] tokens = line.split(",");
//set the user name and score
users.put(tokens[0], Integer.parseInt(tokens[1].trim()));
line = br.readLine();
}
//always close your file
br.close();
}
catch(IOException e)
{
e.printStackTrace();
}
//now sort it using stream apis
Stream<Entry<String, Integer>> sortedMap = users.entrySet().stream()
.sorted(Map.Entry.comparingByValue());
users.entrySet().stream()
.sorted(Map.Entry.comparingByValue()).forEachOrdered(System.out::println);
}