[Java] 객체의 특정 값으로 오름|내림 차순 정렬 (Comparable 사용)

💡 리스트에 있는 객체를 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(리스트) 를 해줘야 리스트 안에서 정렬된다.

 

 

 

댓글

Designed by JB FACTORY