ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java] Stream
    Java 2023. 7. 26. 12:47
    package stream;
    
    public class Dish {
        private final String name;
        private final boolean vegetarian;
        private final int calories;
        private final Type type;
    
        public Dish(String name, boolean vegetarian, int calories, Type type){
            this.name = name;
            this.vegetarian = vegetarian;
            this.calories = calories;
            this.type = type;
        }
    
        public String getName(){
            return name;
        }
    
        public boolean isVegetarian(){
            return vegetarian;
        }
    
        public int getCalories(){
            return calories;
        }
    
        public Type getType(){
            return type;
        }
    
        @Override
        public String toString(){
            return name;
        }
    
        public enum Type { MEAT, FISH, OTHER }
    }

     

    package stream;
    
    import java.util.*;
    import java.util.stream.Collectors;
    
    public class DishTest {
        public static void main(String[] args) {
            List<Dish> menu = Arrays.asList(
                    new Dish("pork", false, 800, Dish.Type.MEAT),
                    new Dish("beef", false, 700, Dish.Type.MEAT),
                    new Dish("chicken", false, 400, Dish.Type.MEAT),
                    new Dish("french fries", true, 530, Dish.Type.OTHER),
                    new Dish("rice", true, 350, Dish.Type.OTHER),
                    new Dish("season fruit", true, 120, Dish.Type.OTHER),
                    new Dish("pizza", true, 550, Dish.Type.OTHER),
                    new Dish("prawns", false, 300, Dish.Type.FISH),
                    new Dish("salmon", false, 450, Dish.Type.FISH)
            );
    
            List<String> threeHighCaloricDishNames =
                    menu.stream() // 메뉴(요리 리스트)에서 스트림을 얻는다.
                            .filter(dish -> dish.getCalories() > 300) // 파이프라인 연산 만들기. 첫 번째로 고칼로리 요리를 필터링 한다
                            .map(Dish::getName) // 요리명 추출
                            .limit(3) // 선착순 세 개만 선택
                            .toList(); // 결과를 다른 리스트로 저장
            System.out.println(threeHighCaloricDishNames); // 결과는 [pork, beef, chicken]
        }
    }

     

    💬 참고

    모던 자바 인 액션 chapter 4장 스트림 소개

    'Java' 카테고리의 다른 글

    [Java] HashSet -> int[]  (0) 2023.07.22
    [Java] PriorityQueue  (0) 2023.07.06
    [Java] HashMap - getOrDefault, keySet()  (0) 2023.07.06
    [Java] 아스키코드표 (ASCII)  (0) 2023.04.10
Designed by Tistory.