Programming/Java

Collections.sort()

사랑우주인 2022. 2. 23. 17:51

오름차순/ 내림차순/ 대소문자 구분 없이 정렬

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class SortArrayList {
public static void main(String[] args) {
// ArrayList 준비
ArrayList<String> list = new ArrayList<>(Arrays.asList("C", "A", "B", "a"));
System.out.println("원본 : " + list); // [C, A, B, a]
// 오름차순으로 정렬
Collections.sort(list);
System.out.println("오름차순 : " + list); // [A, B, C, a]
// 내림차순으로 정렬
Collections.sort(list, Collections.reverseOrder());
System.out.println("내림차순 : " + list); // [a, C, B, A]
// 대소문자 구분없이 오름차순
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
System.out.println("대소문자 구분없이 오름차순 : " + list); // [a, A, B, C]
// 대소문자 구분없이 내림차순
Collections.sort(list, Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER));
System.out.println("대소문자 구분없이 내림차순 : " + list); // [C, B, a, A]
}
}

//출처: https://hianna.tistory.com/569 [어제 오늘 내일]

 

사용자 정의

1. Comparable

2. Comparator

 

Comparable

- 객체의 정렬 방식 정의

- 정렬할 객체가 Comparable interface를 구현

- 자기 자신과 매개변수를 비교

-  compareTo 메소드를 반드시 구현

class Fruit implements Comparable<Fruit> {
private String name;
private int price;
public Fruit(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public int compareTo(Fruit fruit) {
if (fruit.price < price) {
return 1;
} else if (fruit.price > price) {
return -1;
}
return 0;
}
@Override
public String toString() {
return "[ " + this.name + ": " + this.price + " ]";
}
}

//출처: https://hianna.tistory.com/569 [어제 오늘 내일]

 

Comparator

- Custom Comparator

- Collection.sort() 또는 List.sort() 메소드의 파라미터로 전달

- 두 매개변수 객체를 비교

- compare 메소드를 반드시 구현

Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                if (s1.getScore() < s2.getScore()) {
                    return -1;
                } else if (s1.getScore() > s2.getScore()) {
                    return 1;
                }
                return 0;
            }
        });


//출처: https://includestdio.tistory.com/35 [includestdio]

 

오름차순

- 첫번 째 파라미터(또는 자신<- Comparable의 compareTo()에 해당) < 두번 째 파라미터, 리턴 -1 

- 첫번 째 파라미터(또는 자신<- Comparable의 compareTo()에 해당) > 두번 째 파라미터, 리턴 1

- 첫번 째 파라미터(또는 자신<- Comparable의 compareTo()에 해당) == 두번 째 파라미터, 리턴 0

 

내림차순

오름차순에서 부등호 반대