코딩 기록들
[Java Stream Programming] 7. Find & Matching 본문
특정 속성이 데이터 집합에 포함되어있는지 여부를 검색하는 데이터처리
ex) allMatch, anyMatch, noneMatch, findFirst, findAny
anyMatch
- 적어도 한 요소와 일치하는지 확인 -> boolean반환
// 메뉴 스트림에 채식요리가 있는지 확인
if (menu.stream().anyMatch(Dish::isVegerarian)) {
System.out.println("The menu is (somewhat) vegetarian friendly!!");
}
allMatch
- 모든요소가 일치하는지 확인
// 모든 요리가 1000칼로리 이하인지 확인하기
boolean isHealthy = menu.stream()
.allMatch(d -> d.getCalories() < 1000);
noneMatch
- allMatch와 반대처리
- 일치하는요소가 하나도 없는지 확인
boolean isHealthy = menu.stream()
.noneMatch(d -> d.getCalories() >= 1000);
findAny
- 검색하기
- 스트림 내에서 임의요소 가져오기
// 스트림 내에서 임의요소 가져오기
Optional<Dish> dish = menu.stream()
.filter(Dish::isVegerarian)
.findAny();
// 스트림내에서 첫번째요소 가져오기
List<Integer> someNumbers = Arays.asList(1, 2, 3, 4, 5);
Optional<Integer> firstSquarDivisibleByThree =
someNumbers.stream()
.map(x -> x * x)
.filter(x -> x % 3 == 0)
.findFirst();
Optional이란?
- Null 요소를 유연하게 처리할 수 있는 방법
- 네 가지 기능 제공
- isPresent() : Optional이 값을 포함하면 true, 아니라면 false를 반환
- isPresent(Consumer<T> block) : Optional 에 값이 있을 때만 Comsumer를 실행
- T get() : Optional에 값이 있을 경우 값을 반환,
그렇지 않을 경우 “NoSuchElementException” 발생 ->이게 조금 불안정하면 orElse 사용해도 됨 - T orElse(T other) : Optional에 값이 있을 경우 값을 반환. 없을 경우 other 값을 반환
Matching 예제
public class MatchExample {
public static void main(String[] args) {
List<Dish> menu = DishData.menu;
//중간함수 => 전부다 Stream 반환시킴
//filter
//map, flatMap
//distinct
// skip, limit
//peek
//최종함수 <= Steram을 반환시키지 않는것
//forEach : void
//collect : T
//anyMatch : boolean
// Stream 내부에 채식요리가 한개라도 있으면 true, 그렇지 않다면 falses
//방법1
boolean isVegiterian = menu.stream() //Stream<Dish>가 만들어짐
.anyMatch(dish -> dish.isVegetarian());
//방법2
long vegeterianCount = menu.stream()
.filter(dish -> dish.isVegetarian())
.count(); //최종함수 (long을 반환시킴
//방법3 (방법1, 2와 동일)
if(vegeterianCount > 0) {
System.out.println("채식주의자를 위한 요리가 준비되어있습니다!");
}
if(isVegiterian) {
System.out.println("채식주의자를 위한 요리가 준비되어있습니다!");
}
//Stream 내부의 요리가 모두 1000kcal 미만이라면 true
boolean isHealthy = menu.stream()
.allMatch(dish -> dish.getCalories() < 1000);
if (isHealthy) {
System.out.println("우리 식다은 모두 다이어트 식단을 제공합니다!");
}
//Steram 내부의 요리 중 1000kcal를 초과하는 요리가 없다면 true
//allMatch와 반대
isHealthy = menu.stream()
.noneMatch(dish -> dish.getCalories() > 1000);
if(isHealthy) {
System.out.println("우리 식당은 모두 다이어트 식단을 제공합니다! 2");
}
}
}