import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
* [ Lambda 의 기본 틀 ]
* Predicate : (T -> boolean) -> 주로 필터에 사용
* Supplier : (() -> T) -> 만드는놈(객체 생성)
* Consumer : (T -> void) -> 쓰는놈(실행에 사용)
* Function : (T -> R) -> From 에서 뭔가를 To 로 만들어 넘김
*/
public class Main {
public static class Apple {
private String color;
private Integer weight;
public Apple() {}
public Apple(String color, Integer weight) {
this.color = color;
this.weight = weight;
}
public String getColor() {
return color;
}
public Integer getWeight() {
return weight;
}
@Override
public String toString() {
return "Apple{" +
"color='" + color + '\'' +
", weight=" + weight +
'}';
}
}
public static void main(String[] args) throws Exception {
List<Apple> inventory = Arrays.asList(new Apple("green", 50), new Apple("gray", 50), new Apple("pink", 100));
// 무게 오름차순 정렬
inventory.sort(Comparator.comparing(Apple::getWeight));
// 무게 내림차순 정렬
inventory.sort(Comparator.comparing(Apple::getWeight).reversed());
// 무게 오름차순 정렬 (무게가 같으면 색 오름차순 정렬)
inventory.sort(Comparator.comparing(Apple::getWeight).thenComparing(Apple::getColor));
// 무게 오름차순 정렬 (무게가 같으면 색 내림차순 정렬)
Comparator<Apple> reversedColorComparator = Comparator.comparing(Apple::getColor).reversed();
inventory.sort(Comparator.comparing(Apple::getWeight).thenComparing(reversedColorComparator));
for (Apple apple : inventory) {
System.out.println(apple.toString());
}
}
}
출처: https://broduck.tistory.com/6 [개발로 하는 개발]
'JAVA > JAVA 기초' 카테고리의 다른 글
JDBC) 대량 쿼리문 실행 for SQLite (0) | 2022.05.21 |
---|---|
JDBC (0) | 2022.05.17 |
스트림 (Stream) (0) | 2022.03.29 |
람다식 (0) | 2022.03.29 |
컬렉션 프레임워크 (Collection Framework) (0) | 2022.03.29 |
댓글