Modern java in action

[Modern java in action] Stream(2)

상국이 2021. 6. 24. 15:00
728x90

4-1 필터링

→ 스트림의 요소를 선택하는 방법

    1) 프레디케이트로 필터링

    → 스트림 인터페이스는 filter 메서드를 지원한다. filter메서드는 Predicate(boolean을 반환하는 함수)를 인수로 받아서 일치하는 모든 스트림을 반환한다. 

 

예시)

프레디케이트 필터링

List<Dish> vegetarianMenu = menu.stream()
                                .filter(Dish::isVegetarian)
                                .collect(toList());

2) 고유 요소 필터링

    → 고유 요소로 이루어진 스트림을 반환하는 distinct 메서드도 지원한다. (고유 여부는 스트림에서 만든 객체의 hashCode, equals로 결정됨)

 

예시)

고유 요소 필터링

 

List<Integer> numbers = Arrays.asList(1,2,1,3,3,2,4);
numbers.stream()
       .filter(i -> i % 2 ==0)
       .distinct()
       .forEach(System.out::println);       //2,4

 

4-2 스트림 슬라이싱

→ 스트림의 요소를 선택하거나 스킵하는 다양한 방법

    1) 프레디케이트를 이용한 슬라이싱

TAKEWHILE 활용 : 조건에 해당하는 경우가 나온 경우 반복 작업을 중단할 수 있음 (정렬된 경우 사용)

 

TAKEWHILE 활용

List<Dish> specialMenu = Arrays.asList(
        new Dish("seasonal fruit", true, 120, Dish.Type.OTHER),
        new Dish("prawns", false, 300, Dish.Type.FISH),
        new Dish("rice", true, 350, Dish.Type.OTHER),
        new Dish("chicken", false, 400, Dish.Type.MEAT),
        new Dish("french fries", true, 530, Dish.Type.OTHER)
);
 
List<Dish> slicedMenu1 = specialMenu.stream()
                                    .takeWhile(dish -> dish.getCalories() < 320)
                                    .collect(toList());                        
                                    //seasonal fruit, prawns목록

 

DROPWHILE 활용 : TAKEWHILE와 정반대 작업 수행

 

DROPWHILE 활용

List<Dish> specialMenu = Arrays.asList(
        new Dish("seasonal fruit", true, 120, Dish.Type.OTHER),
        new Dish("prawns", false, 300, Dish.Type.FISH),
        new Dish("rice", true, 350, Dish.Type.OTHER),
        new Dish("chicken", false, 400, Dish.Type.MEAT),
        new Dish("french fries", true, 530, Dish.Type.OTHER)
);
 
List<Dish> slicedMenu1 = specialMenu.stream()
                                    .dropWhile(dish -> dish.getCalories() < 320)
                                    .collect(toList());                        
                                    //rice, chickenm, french fries목록

    2) 스트림 축소

limit : 주어진 값 이하의 크기를 갖는 새로운 스트림을 반환

 

limit

List<Dish> slicedMenu1 = specialMenu.stream()
                                    .filter(dish -> dish.getCalories() > 300)
                                    .limit(3)
                                    .collect(toList());                        
                                    //rice, chickenm, french fries목록

    3) 요소 건너뛰기

skip : 처음 n개 요소를 제외한 스트림을 반환

 

skip

List<Dish> slicedMenu1 = specialMenu.stream()
                                    .filter(dish -> dish.getCalories() > 300)
                                    .skip(2)
                                    .collect(toList());
728x90