[Java] Java 8: Stream API

sj·2022년 12월 4일

Java

목록 보기
6/7

Stream 이란?

배열이나 컬렉션에 담긴 데이터를 다룰 때, 반복문이나, iterator를 사용하면 코드가 길어지고, 가독성이 떨어진다. 이 문제를 해결하기위해 Stream API 등장.

  • 특징
    • 스트림은 데이터를 변경하지 않는다. → Immutable
    • 스트림은 재사용이 불가. → 최종 연산이 실행된 후 재사용 불가.
  • 스트림 파이프라인
    • 0 ~ N 개의 중개 연산과 1개의 종료 연산으로 구성.
  • 중개 연산
    • Stream을 리턴.
  • 종료 연산
    • Stream을 리턴하지 않는다.

대표 Stream

  • 중개 연산자
    • 필터링 : filter, distinct
    • 변환 : map, flatMap
    • 제한 : limit, skip
    • 정렬 : sorted
  • 최종 연산
    • 요소 출력 : forEach
    • 요소 검색 : findFirst, findAny
    • 요소 통계 : count, min, max
    • 요소 연산 : sum, average
    • 요소 수집 : collect

예시

  • filter + anyElement / firstElement
    List<String> elements = Stream.of("a", "b", "c")
    										.filter(element -> element.contains("b"))
                        .collect(Collectors.toList());
    
        Optional<String> anyElement = elements.stream().findAny();
        System.out.println(anyElement.orElse("암것두 없어"));
    
        Optional<String> firstElement = elements.stream().findFirst();
        System.out.println(firstElement.orElse("한개두 없어"));
  • N개의 중개 연산자
    Stream<String> onceModifiedStream = Stream.of("abcd", "bbcd", "cbcd");
    
    Stream<String> twiceModifiedStream = onceModifiedStream
    										.skip(1)
    										.map(element -> element.substring(0, 3));
    
    System.out.println(twiceModifiedStream); //?
    System.out.println(twiceModifiedStream.collect(Collectors.toList()));
  • map 활용
    class Product {
        private int age;
        private String name;
    
        public Product(int age, String name) {
            this.age = age;
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public String getName() {
            return name;
        }
    }
    List<Product> productList = Arrays.asList(
    								new Product(23, "potatoes"),
                    new Product(14, "orange"), new Product(13, "lemon"),
                    new Product(23, "bread"), new Product(13, "sugar")
    );
    
    List<String> collectorCollection = productList.stream()
    				.map(Product::getName)
    				.collect(Collectors.toList());
    
    System.out.println(collectorCollection);
    
    double averageAge = productList.stream()
                    .collect(Collectors.averagingInt(Product::getAge));
    System.out.println("나이 평균 : " + averageAge);
    
    int summingAge = productList.stream().mapToInt(Product::getAge).sum();
            System.out.println("나이 총합 : " + summingAge);

0개의 댓글