我在 Java 8 中有一個二維陣列:
String data[][] = new String[i][2];
它看起來像這樣:
Player1 8 Player5 3 Player3 9 Player4 5 ...
我想對它進行排序,使其得分最高:
Player3 9 Player1 8 Player4 5 Player5 3
我該如何對其進行排序,或者是否有更好的方法來保存并在之后對其進行排序?
我已經嘗試在這里搜索解決方案,但只找到了這個:
String[][] out = Arrays.stream(data).sorted(Comparator.comparing(x -> -Integer.parseInt(x[1]))).toArray(String[][]::new);
但這在我的情況下不起作用
uj5u.com熱心網友回復:
面向物件設計
考慮使用面向物件的設計,這意味著讓實際物件代表每個玩家,而不是二維陣列中的行。這是一種很好的編碼實踐,因為它提高了可讀性和可除錯性。它還可以幫助您的代碼的讀者更好地理解它。
像這樣的東西可以解決問題:
class Player {
String name;
int score;
}
這允許您創建許多“Player”實體,每個實體都有自己的名稱(例如“player1”或任何其他文本)和自己的分數。
雖然這樣更好,但仍然可以通過命名 player 來改進final。這意味著一旦在建構式中分配它就不能更改:
class Player {
final String name; // we made this final
int score;
Player(String name) { // this is the constructor
this.name = name;
}
}
我們可以改進代碼的另一種方法是制作 fields private,這意味著它們的值只能以我們允許的方式更改。
class Player {
private final String name; // we made this
private int score; // and this, private
Player(String name) {
this.name = name;
}
public int getScore() { // so we need a getter
return score;
}
public void setScore(int score) { // and a setter, for score
this.score = score;
}
public String getName() { // we also need a getter for name
return name; // but no setter, because it is final
}
}
Using this technique, you can set limits for score, for example not allowing to be negative, or more than 1000. Or you can omit the setter and instead have an addScore method that only allows increasing the score of a player.
After we have our class, we can create however many players we want, like this:
Player p1 = new Player("player1");
And then we can access its methods like setting and getting score like this:
int s = p1.getScore();
p1.setScore(s*2); // doubles the score of player1
Sorting
To be able to sort objects in arbitrary ways, we would need to put them in data structures or "collections", like lists. You had used an array which is a very primitive data structure whose length cannot be increased or decreased once it is created.
To put your players in a list, simply create a list and add them to it like this:
List<Player> players = new ArrayList<>();
players.add(p1);
After you have added all your players into a list, you can sort the players in the list based on their score, like this:
players.sort(Comparator.comparingInt(Player::getScore))
You can even sort them by their names if you want:
players.sort(Comparator.comparing(Player::getName));
If you want to learn what that :: symbol means, read more about "method reference".
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/448629.html
