3 minute read

드디어 프로젝트가 끝이나고 쉴여우가 생겨 다시 쓰는 포스트

드디어 프로젝트가 90퍼 정도가 끝이나고 여유가 생겨 포스트를 계속 적어보려 한다.

어떤 글부터 적어야할까 하다, 이전에 적었던 java Comparable & Compartor 에 대해 마무리 하고, 조금더 응용을 하고자 하여 이글을 적어본다.

0. 들어가기전에

이번장에선 장에선 이전에 배운 Comparavle을 응용해보는 시간을 가져보려한다.

우리는 이전에 프리미어 리그 순위의 승점 정렬에 대해 알아보았다. 그러면 이번엔 개인 순위에 대해 알아보고 싶다.

프리미어리그에서 득정왕은 어떻게 정해질까?

당연히 가장 많은 득점을한 선수가 득점왕이될것이다. 하지만 득점이 같다면 그다음은 어떻게 진행이 될까??

출장 경기시간이 적고 그다음은 도움기록까지 비교하여 결정이 되게 된다.

그러면 이제 이 순위를 정렬 해보도록 하자.

1. 이중비교

손흥민 선수의 20-21 득점왕을 기원하며 이 포스트를 적어봅니다.

손흥민 출처는 스포츠 조선

1-1 득점만 비교

Main.java

package com.company;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        List<Player> topPlayer = new ArrayList<>();

        Player p1 = new Player("손흥민", 34, 36, 10);
        Player p2 = new Player("헤리케인", 33, 16, 16);
        Player p3 = new Player("아구에로", 28, 30, 5);

        topPlayer.add(p1);
        topPlayer.add(p2);
        topPlayer.add(p3);

        Collections.sort(topPlayer);

        System.out.println(topPlayer);
    }
}

Player.java

public class Player implements Comparable<Player>{

    private String playerName;
    private Integer appearances;
    private Integer goal;
    private Integer assist;


    public Player() {
    }

    public Player(String playerName, Integer appearances, Integer goal, Integer assist) {
        this.playerName = playerName;
        this.appearances = appearances;
        this.goal = goal;
        this.assist = assist;
    }

    @Override
    public String toString() {
        return "Player{" +
                "playerName='" + playerName + '\'' +
                ", appearances=" + appearances +
                ", goal=" + goal +
                ", assist=" + assist +
                '}' + "\n";
    }

    @Override
    public int compareTo(Player o) {
        return o.goal - this.goal;
    }
}

출력 결과 :
[Player{playerName='손흥민', appearances=34, goal=36, assist=10}
, Player{playerName='아구에로', appearances=28, goal=30, assist=5}
, Player{playerName='헤리케인', appearances=33, goal=16, assist=16}
]

여기에 지금 칼버트 루윈 선수와 제이미 바디 선수가 득점왕 경쟁에 참여하게 됩니다.

Player p4 = new Player("칼버트 르윈", 36, 36, 5);
Player p5 = new Player("제이미 바디", 34, 36, 7);

topPlayer.add(p4);
topPlayer.add(p5);

위와 같이 추가 한다면 우리가 원하는 결과가 제대로 나올까??? 그렇지 못할것이다. 그렇다면 어떻게 할까 ?? Player 클래스를 조금 수정하도록 하자, Player.java

@Override
    public int compareTo(Player o) {
        if (o.goal == this.goal) {
            if(this.appearances == o.appearances) {
                return o.assist - this.assist;
            } else {
                return this.appearances - o.appearances;
            }
        } else {
            return o.goal - this.goal;
        }
    }

결과

[Player{playerName='손흥민', appearances=34, goal=36, assist=10}
, Player{playerName='제이미 바디', appearances=34, goal=36, assist=7}
, Player{playerName='칼버트 르윈', appearances=36, goal=36, assist=5}
, Player{playerName='아구에로', appearances=28, goal=30, assist=5}
, Player{playerName='헤리 케인', appearances=33, goal=16, assist=16}
]

끝끝 이제 원하는 득점왕 정렬이 되었다. 사용법이 굉장히 편리하여 응용하여 사용하기가 정말 편리하다.

2. 응용 비교

여기서 뭘더 응용해볼까 하다, 이러한 자바가 알아서 순서를 잘 정해주는 1,2,3,4 a,b,c,d 가 아닌 내가 스스로 정한 텍스트에 순서를 부여하는 방법또한 많이 쓰이므로 이 응용또한 남긴다.

위의 골 결정 순위는 다 필요없다, 내 마음속 순위를 정하려 한다.

손흥민, 아구에로, 바디, 헤리케인, 르윈 순서로 정렬이 가능할까?

당연히 넣는 순서로 그냥 sort하면 되지만 이걸 원하는게 아닌건 모두가 알기에

무작위로 넣어을때, 이와같이 순서를 보장할 방법은 아래와 같다.

Main.java

package com.company;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        List<Player> topPlayer = new ArrayList<>();

        Player p1 = new Player("손흥민", 34, 36, 10);
        Player p2 = new Player("헤리 케인", 33, 16, 16);
        Player p3 = new Player("아구에로", 28, 30, 5);
        Player p4 = new Player("칼버트 르윈", 36, 36, 5);
        Player p5 = new Player("제이미 바디", 34, 36, 7);

        // 한골의 손흥민은 과연 몇등일까?
        Player p6 = new Player("손흥민", 38, 1, 1);



        topPlayer.add(p1);
        topPlayer.add(p2);
        topPlayer.add(p3);
        topPlayer.add(p4);
        topPlayer.add(p5);
        topPlayer.add(p6);



        Collections.sort(topPlayer);

        System.out.println(topPlayer);
    }
}

아래 player.java 에서 getRankNum 과 compareTo method만 확인하면 됩니다.

Player.java

package com.company;

public class Player implements Comparable<Player>{

    private String playerName;
    private Integer appearances;
    private Integer goal;
    private Integer assist;


    public Player() {
    }

    public Player(String playerName, Integer appearances, Integer goal, Integer assist) {
        this.playerName = playerName;
        this.appearances = appearances;
        this.goal = goal;
        this.assist = assist;
    }

    @Override
    public String toString() {
        return "Player{" +
                "playerName='" + playerName + '\'' +
                ", appearances=" + appearances +
                ", goal=" + goal +
                ", assist=" + assist +
                '}' + "\n";
    }

    private Integer getRankNum(String playerName) {
        switch (playerName) {
            case "손흥민" :
                return 0;
            case "아구에로" :
                return 1;
            case "제이미 바디" :
                return 2;
            case "헤리 케인" :
                return 3;
            case "칼버트 르윈" :
                return 4;
        }
        return 99;
    }

    @Override
    public int compareTo(Player o) {
        if(o.playerName == this.playerName) {
            if (o.goal == this.goal) {
                if(this.appearances == o.appearances) {
                    return o.assist - this.assist;
                } else {
                    return this.appearances - o.appearances;
                }
            } else {
                return o.goal - this.goal;
            }
        } else {
            return getRankNum(this.playerName) - getRankNum(o.playerName);
        }


    }
}

출력결과

[Player{playerName='손흥민', appearances=34, goal=36, assist=10}
, Player{playerName='손흥민', appearances=38, goal=1, assist=1}
, Player{playerName='아구에로', appearances=28, goal=30, assist=5}
, Player{playerName='제이미 바디', appearances=34, goal=36, assist=7}
, Player{playerName='헤리 케인', appearances=33, goal=16, assist=16}
, Player{playerName='칼버트 르윈', appearances=36, goal=36, assist=5}
]

1골의 손흥민이 36골 손흥민 다음에 위치한걸 확인할수 있다. :0

오늘도 11시에 경기가 있던데, 꼭 득점하였으면 좋겠다,

Categories:

Updated: