Java Comparator usage
I'm fairly new to java thus the question. My task is to create a class Checker which uses a comparator desc to sort the players. The sorting logic is to sort the players in decreasing order by score and then if two players have the same score, the one whose name is lexicographically larger should appear first.
This is the Player class
class Player
{
String name;
int score;
}
The Comparator gets called this way
Checker check=new Checker();
.................
Arrays.sort(Player,check.desc);
This is what I tried,
class Checker implements Comparator<Player>{
public int compare(Player p1, Player p2){
if(p1.score < p2.score) return 1;
else if(p1.score > p2.score) return -1;
else if(p1.score == p2.score){
if(p1.name.compareTo(p2.name) < 0) return 1;
else if(p1.name.compareTo(p2.name) > 0) return -1;
else if (p1.name.compareTo(p2.name) == 0) return 0;
}
}
}
Could someone help me get it right. I don't really understand how desc
can be an attribute of the checker
class.
If you are allowed to use Comparator
in your solution then it's actually quite a bit simpler than you think.
Comparator<Player> playerSorted = Comparator
.comparingInt(Player::getScore)
.thenComparing(Player::getName)
.reversed();
If you need to wrap it in another class then you can declare this Comparator
as a private static final
and delegate the compare
method to it.
class Checker implements Comparator<Player> {
private static final Comparator<Player> SORT_ASC = Comparator
.comparingInt(Player::getScore).thenComparing(Player::getName);
private static final Comparator<Player> SORT_DESC = SORT_ASC.reversed();
private final boolean descending;
public int compare(Player player1, Player player2) {
Comparator<Player> sorter = descending ? SORT_DESC : SORT_ASC;
return sorter.compare(player1, player2);
}
}
链接地址: http://www.djcxy.com/p/91938.html
上一篇: 初始化对istream的引用
下一篇: Java比较器的用法