본문 바로가기
Tech-Java

Collection의 Sort 재정의 - Comparator

by redcrow 2017. 8. 20.

정렬기준이 존재하지 않는 클래스의 Collection의 사용자정의 정렬를 위한 Interface , Comparaor<T> 의 사용예제입니다.


아래는 학생의 점수를 기준으로 내림차순으로 정렬하는 예제입니다.


import java.util.*;


public class ComparatorTest {


public static void main(String[] args) {

StudentScore sc1 = new StudentScore("001", 98);

StudentScore sc2 = new StudentScore("002", 88);

StudentScore sc3 = new StudentScore("003", 62);

StudentScore sc4 = new StudentScore("004", 88);

StudentScore sc5 = new StudentScore("005", 99);

StudentScore sc6 = new StudentScore("006", 72);

ArrayList<StudentScore> al = new ArrayList<StudentScore>();

al.add(sc1);

al.add(sc2);

al.add(sc3);

al.add(sc4);

al.add(sc5);

al.add(sc6);


al.sort(new Comparator<StudentScore>(){

   //compare의 값이 음수이면 내림차순, 양수이면 올림차순

public int compare(StudentScore a , StudentScore b){

return  b.score - a.score;

}

}

);



     //출력하기

     int rank =1;;

for(StudentScore sc : al) {

System.out.println("Rank :" + rank + ","+ sc.studentNumber + ":" +  sc.score);

 rank++;

}

}

}


class StudentScore {

String studentNumber = "";

int score = 0;

public StudentScore(String studentNumber, int score){

this.studentNumber = studentNumber;

this.score = score;

}

}


다음은  Map<K,V>를 사용해서 정렬하는 방법


import java.util.*;



public class ComparatorTest2 {

public static void main(String[] args) {

Map<String,Integer> hm = new HashMap<String, Integer>();

hm.put("001", 98);

hm.put("002", 88);

hm.put("003", 62);

hm.put("004", 88);

hm.put("005", 99);

hm.put("006", 72);

List<Map.Entry<String, Integer>> li = new LinkedList<Map.Entry<String,Integer>>(hm.entrySet());

li.sort(new Comparator<Map.Entry<String, Integer>>(){

public int compare(Map.Entry<String, Integer> o1 , Map.Entry<String, Integer> o2){

return o2.getValue() - o1.getValue() ;

}

}

);

int rank = 1;

for(Map.Entry<String, Integer> map : li) {


System.out.println("Rank :" + rank + ","+ map.getKey() + ":" +  map.getValue());

rank++;

}

}

}


'Tech-Java' 카테고리의 다른 글

자주쓰는 Excpression  (0) 2018.04.25
Java 잊기쉬운거  (0) 2018.04.19
기타등등  (0) 2017.04.02
Java에서 정규표현식(Regular Expression) 사용하기  (0) 2016.11.06
Garbage Collection  (0) 2016.03.17

댓글