[문제]
Product 객체 리스트를 가격 오름차순으로 정렬하여 출력하세요.
[데이터]
new Product("Laptop", 1500)
new Product("Phone", 800)
new Product("Tablet", 500)
new Product("Monitor", 300)
[요구사항]
- `sorted()` 메서드로 가격 오름차순 정렬
- Comparator.comparingInt() 사용
- 결과 출력
[소스]
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class StreamObjectSort {
// 간단한 Product 클래스
static class Product {
String name;
int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
@Override
public String toString() {
return name + " : " + price + "$";
}
}
public static void main(String[] args) {
List<Product> products = Arrays.asList(
new Product("Laptop", 1500),
new Product("Phone", 800),
new Product("Tablet", 500),
new Product("Monitor", 300)
);
System.out.println("원본 상품 리스트:");
products.forEach(System.out::println);
// sorted()와 Comparator.comparingInt()로 가격 오름차순 정렬
List<Product> sorted = products.stream()
.sorted(Comparator.comparingInt(Product::getPrice)) // 가격 오름차순
.collect(Collectors.toList());
System.out.println("\n가격 오름차순 정렬:");
sorted.forEach(System.out::println);
}
}