[Java] 객체의 특정 값으로 오름|내림 차순 정렬 (Comparable 사용)
- 📕 Programing/Java
- 2022. 4. 27. 13:24
💡 리스트에 있는 객체를 Comparable를 활용하여 객체의 특정값으로 정렬하기
package org.kyhslam.inflearnJava.dp;
import java.util.ArrayList;
import java.util.Collections;
class Brick implements Comparable<Brick> {
public int s,h,w;
public Brick(int s, int h, int w) {
this.s = s;
this.h = h;
this.w = w;
}
@Override
public int compareTo(Brick o) {
//return o.s - this.s; // 내림차순
return this.s - o.s; // 오름차순
}
}
public class dp_04 {
public static void main(String[] args) {
ArrayList<Brick> list = new ArrayList<>();
list.add(new Brick(10, 2, 3));
list.add(new Brick(5, 4, 1));
list.add(new Brick(7, 7, 4));
System.out.println("list = " + list);
list.forEach(s -> System.out.println(s.s + ", " + s.h + " , " + s.w));
//10, 2 , 3
//5, 4 , 1
//7, 7 , 4
System.out.println("---------------");
Collections.sort(list);
list.forEach(s -> System.out.println(s.s + ", " + s.h + " , " + s.w));
//5, 4 , 1
//7, 7 , 4
//10, 2 , 3
}
}
#### 결과
10, 2 , 3
5, 4 , 1
7, 7 , 4
---------------
5, 4 , 1
7, 7 , 4
10, 2 , 3
- 참고로 오버라이드한 compareTo 메서드 값을 반대로 하면 내림 차순 정렬이 된다.
- 리스트에 객체를 넣고 꼭 Collections.sort(리스트) 를 해줘야 리스트 안에서 정렬된다.
'📕 Programing > Java' 카테고리의 다른 글
[Java] equals() / hashcode() (1) | 2023.04.30 |
---|---|
[Java] SFTP 사용하여 파일 업로드 (0) | 2023.02.14 |
[Java] HTTP 방식으로 POST 통신 (1) | 2021.11.02 |
[Java] Steam의 filter 예제 (0) | 2021.10.14 |
[Java] 특정 객체의 값을 오름|내림 차순 정렬 (Comparator ) (0) | 2021.10.14 |