ArrayList
에 저장된 사용자 정의 객체를 특정 속성 값으로 정렬해야 하는 상황은 개발에서 매우 자주 발생합니다. 예를 들어 Product
라는 클래스가 있고, 그 안에 price
라는 속성이 있다고 가정해 보겠습니다. 이번 글에서는 price
뿐만 아니라 다양한 클래스 속성을 기준으로 오름차순과 내림차순 정렬을 수행하는 방법을 단계별로 설명합니다.
1. 문제 정의
다음과 같이 ArrayList<Product>
에 상품 목록이 저장되어 있다고 합시다.
이 리스트를 가격(price
) 기준으로 정렬하는 것이 목표입니다.
class Product {
private double price;
private String name;
public Product(double price, String name) {
this.price = price;
this.name = name;
}
public double getPrice() { return price; }
public String getName() { return name; }
}
2. Comparator를 이용한 정렬
자바 8 이후에는 Comparator
와 메서드 참조(::
)를 활용해 훨씬 간결하게 정렬할 수 있습니다.
오름차순 정렬
list.sort(Comparator.comparingDouble(Product::getPrice));
내림차순 정렬
list.sort(Comparator.comparingDouble(Product::getPrice).reversed());
comparingDouble
은 double
형 속성에 사용하며,int
, String
, Date
등의 타입에도 비슷한 방식으로 적용할 수 있습니다.
3. 속성 타입별 Comparator 예시
데이터 타입 | Comparator 예시 | 설명 |
---|---|---|
int |
Comparator.comparingInt(Employee::getAge) |
나이 기준 정렬 |
double |
Comparator.comparingDouble(Product::getPrice) |
가격 기준 정렬 |
String |
Comparator.comparing(Student::getName) |
이름 기준 정렬 |
Date |
Comparator.comparing(Task::getCreatedDate) |
생성일 기준 정렬 |
내림차순으로 바꾸고 싶다면 .reversed()
를 추가하면 됩니다.
list.sort(Comparator.comparing(Product::getName).reversed());
4. Collections.sort()를 이용한 전통적인 방식
자바 8 이전에는 Collections.sort()
와 익명 클래스를 함께 사용하는 방법이 일반적이었습니다.
Collections.sort(list, new Comparator<Product>() {
@Override
public int compare(Product a, Product b) {
return Double.compare(b.getPrice(), a.getPrice()); // 내림차순
}
});
람다식을 사용하면 코드가 훨씬 간결해집니다.
list.sort((a, b) -> Double.compare(b.getPrice(), a.getPrice()));
5. 여러 기준으로 정렬하기
정렬 기준이 두 가지 이상일 때는 thenComparing()
을 사용할 수 있습니다.
list.sort(
Comparator.comparingDouble(Product::getPrice).reversed()
.thenComparing(Product::getName)
);
이 코드는 가격을 내림차순으로 정렬하고,
가격이 같을 경우 이름을 기준으로 오름차순 정렬합니다.
6. 전체 예제 코드
import java.util.*;
class Product {
private double price;
private String name;
public Product(double price, String name) {
this.price = price;
this.name = name;
}
public double getPrice() { return price; }
public String getName() { return name; }
}
public class Main {
public static void main(String[] args) {
ArrayList<Product> list = new ArrayList<>();
list.add(new Product(19.99, "Keyboard"));
list.add(new Product(49.99, "Mouse"));
list.add(new Product(9.99, "Cable"));
// 가격 기준 내림차순 정렬
list.sort(Comparator.comparingDouble(Product::getPrice).reversed());
// 결과 출력
for (Product p : list) {
System.out.println(p.getName() + " : $" + p.getPrice());
}
}
}
출력 결과:
Mouse : $49.99
Keyboard : $19.99
Cable : $9.99
7. 정리
Comparator
는 객체의 특정 속성을 기준으로 정렬할 때 가장 직관적이고 강력한 도구입니다.comparing()
,reversed()
,thenComparing()
을 조합하면 다양한 정렬 기준을 쉽게 구현할 수 있습니다.- 자바 8 이상에서는 람다식과 메서드 참조를 활용해 코드를 짧고 명확하게 유지할 수 있습니다.
- 실제 프로젝트에서는 정렬 기준을 별도의 메서드로 분리해 관리하면 재사용성이 높아집니다.
반응형
'개발 (Development) > Java' 카테고리의 다른 글
[Java/Spring Boot] "No thread-bound request found" 에러 원인과 해결법 (0) | 2025.09.19 |
---|---|
[Java/Spring Boot] JdbcTemplate으로 여러 데이터베이스 연결하기 (0) | 2025.09.14 |
[Java/Spring Boot] Spring Boot에서 OAuth2 인증 401 오류 해결하기 (0) | 2025.09.14 |
[Java] JPA에서 DTO는 Interface로 구현할까? Class로 구현할까? (4) | 2025.08.03 |
[Java] Interface란? 클래스와 다른 점은? (0) | 2025.08.03 |