자바에서 사용하는 객체들을 정렬해야하는 경우가 있다. 이럴 때, Comparator, Comparable 인터페이스를 활용해서 비교가 가능하다.
( 매우 유용하다고 생각되는 기능이니 잘 정리해 두는 것이 좋겠다.)
class Player implements Comparable<Player>{
int score ;
int name ;
int age;
public Player(int score, String name){
this.score = score;
this.name = name;
}
//compareTo의 return 값이 양수면 객체 sort교환o
//return 값이 음수면 객체 sort교환 x
@Override
public int compareTo(Player o){
//내림차순 정렬할 경우
return o.getScore() -getScore();
}
}
class main{
ArrayList<Player> players = new ArrayList<>();
players.add(new player(99,"호성"));
players.add(new player(25,"구령"));
players.add(new player(120,"호구미"));
//player 객체에 Comparable interface implements 해놓았기 때문에 Collections 비교 가능
Collections.sort(players)
}
class Player implements Comparable<Player>{
int score ;
int name ;
int age;
public Player(int score, String name){
this.score = score;
this.name = name;
}
}
class main{
ArrayList<Player> players = new ArrayList<>();
players.add(new player(99,"호성"));
players.add(new player(25,"구령"));
players.add(new player(120,"호구미"));
//람다식을 활용하여 익명 comparator 객체를 만들어서 적용할 수 있다.
Collections.sort(players,(player1,player2)->{
if(player1.score ==player2.score){
//점수가 같을 때 나이를 오름차순으로 정렬
return player1.age-player2.age
}
});
}
class Player implements Comparable<Player>{
int score ;
int name ;
int age;
public Player(int score, String name){
this.score = score;
this.name = name;
}
}
class main{
ArrayList<Player> players = new ArrayList<>();
players.add(new player(99,"호성"));
players.add(new player(25,"구령"));
players.add(new player(120,"호구미"));
Comparator<Player> comparator = new Comparator<player>(){
@Override
public int compare(Player a , player b){
if(a.score ==b.score){
//점수가 같을 때 나이를 오름차순으로 정렬
return a.age-b.age
}
}
}
//위에 만든 compartor 객체를 활용해서 ArrayList 정렬가능
Collections.sort(players,comparator);
}