Я думаю, вам нужно создать объект для хранения того, что представляет собой один экземпляр данных табло. Name:Score:Level
. Когда вы читаете данные из файла, читайте его как List
из ScoreBoardScore
. List<ScoreBoardScore>
. Один из способов сортировки List
из ScoreBoardScore
- использовать Collections.sort
. Пример кода ниже. Комментарии в коде.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
* @author Sedrick
*/
public class Main
{
public static void main(String[] args)
{
List<ScoreBoardScore> scoreBoardScores = getScoreFromFile();//get List of ScoreBoardScore from file.
scoreBoardScores.forEach(System.out::println);//Print scores before sort.
//sort data
//This sorts in decending order. To get acending order change if(o1.getScore() < o2.getScore()) to if(o1.getScore() > o2.getScore())
Collections.sort(scoreBoardScores, Comparator.comparingInt(ScoreBoardScore::getScore).reversed());
System.out.println("\nAfter Sort:");
scoreBoardScores.forEach(System.out::println);//Print scores after sort.
}
static List<ScoreBoardScore> getScoreFromFile()
{
//simulate reading a file and returning a List of Scores
String fakeFileData = "John Doe 91 8\n"
+ "jane Doe 100 9\n"
+ "Kim Johnson 88 7\n"
+ "Kim Johnson 95 8";
List<String> lines = new ArrayList(Arrays.asList(fakeFileData.split("\n")));//These simulate the lines of a file.
List<ScoreBoardScore> scoreBoardScores = new ArrayList();
for(int i = 0; i < lines.size(); i++)//loop through the lines and split the data based on more than two spaces. I didn't use one space or more because the name has one space.
{
String[] splitData = lines.get(i).split("\\s{2,}");//Split on two or more spaces
scoreBoardScores.add(new ScoreBoardScore(splitData[0], Integer.parseInt(splitData[1]), splitData[2]));//Use the data to create ScoreBoardScores.
}
return scoreBoardScores;
}
}
Вывод:
--- exec-maven-plugin:1.5.0:exec (default-cli) @ JavaTestingGround ---
ScoreBoardScore{score=91, name=John Doe, level=8}
ScoreBoardScore{score=100, name=jane Doe, level=9}
ScoreBoardScore{score=88, name=Kim Johnson, level=7}
ScoreBoardScore{score=95, name=Kim Johnson, level=8}
After Sort:
ScoreBoardScore{score=100, name=jane Doe, level=9}
ScoreBoardScore{score=95, name=Kim Johnson, level=8}
ScoreBoardScore{score=91, name=John Doe, level=8}
ScoreBoardScore{score=88, name=Kim Johnson, level=7}
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 1.673 s
Finished at: 2019-12-11T14:25:58-06:00
Final Memory: 12M/40M
------------------------------------------------------------------------