학습 정리 - Java Stream & Comparator (0709)
✅ 1. Stream API 해당 기능 정리
1.1 map (매핑)
- 스트림 요소를 변형할 때 사용
- 예: Apple 객체 리스트에서 색상만 추출
List<Color> colorList = apples.stream()
.map(Apple::getColor)
.collect(Collectors.toList());
1.2 filter (필터링)
- 조건을 매칭하는 요소만 필터링
- 예: 채신 요리만 추출
List<Dish> vegetarianDishes = menuList.stream()
.filter(Dish::isVegetarian)
.collect(Collectors.toList());
1.3 distinct (중복 제거)
- 중복 요소 제거 (equals, hashCode 필요)
List<Integer> distinctEvens = numbers.stream()
.filter(n -> n % 2 == 0)
.distinct()
.collect(Collectors.toList());
1.4 limit / skip
- limit(n): 앞에서 n개 추출
- skip(n): 앞에서 n개 건너뛰기
List<Dish> top3Calories = menuList.stream()
.filter(d -> d.getCalories() > 300)
.limit(3)
.collect(Collectors.toList());
1.5 sorted (정렬)
List<Dish> sorted = menuList.stream()
.sorted(Comparator.comparing(Dish::getCalories))
.collect(Collectors.toList());
✅ 2. Comparator 사용법 요약
| 메서드 | 설명 |
|---|
| comparing() | 틀즈 필드 기준 정렬 |
| reversed() | 정렬 결과를 반전 (내림차순) |
| thenComparing() | 1차 정렬이 같을 때 다음 조건 지정 |
menuList.stream()
.sorted(Comparator.comparing(Dish::getCalories).reversed())
.forEach(System.out::println);
✅ 3. 실습 예시 요약
- 무게 200 이상이고 색상이 빨강 사과만 필터링
List<Apple> redHeavyApples = apples.stream()
.filter(a -> a.getWeight() >= 200)
.filter(a -> a.getColor().equals("red"))
.collect(Collectors.toList());
- 400칼로리 이하인 요리 중 칼로리 낮은 순으로 3개 추출
List<Dish> topDishes = menuList.stream()
.filter(d -> d.getCalories() <= 400)
.sorted(Comparator.comparing(Dish::getCalories))
.limit(3)
.collect(Collectors.toList());
✅ 요약 정리
- map: 원하는 필드 추출
- filter: 조건 거래내기
- distinct: 중복 제거
- limit, skip: 추출 개수 조절
- sorted: 정렬 기준 설정
- Comparator: 정렬 조건 지정 및 조합 (reversed, thenComparing)
- 연습 시 연속적으로 연결해서 필터/정렬/출력 가능