본문 바로가기

Java

Stream(2)

Stream(2)

동작 순서

  • 모든 요소가 중간 연산을 수행하고 전체 결과를 가지고 다음 연산으로 넘어가는 것이 아니라
    한 요소가 모든 파이프라인을 거쳐서 결과를 만들어낸 후 다음 요소로 넘어간다.
List<String> names = Arrays.asList("Kim", "Lee", "Park", "Choi");

List<String> namesList = names.stream()
        .filter(el -> {
            System.out.println("filter() called, now element is " + el);
            return el.contains("i");
        })
        .map(el -> {
            System.out.println("map() called, now element is " + el);
            return el.toUpperCase();
        })
        .collect(Collectors.toList());
        
System.out.println(namesList);

// [실행 결과]
// filter() called, now element is Kim
// map() called, now element is Kim
// filter() called, now element is Lee
// filter() called, now element is Park
// filter() called, now element is Choi
// map() called, now element is Choi
// [KIM, CHOI]

 

성능 향상

  • 스트림은 한 요소씩 수직적으로 실행된다.
  • 요소의 범위를 줄이는 작업을 먼저 실행하면 불필요한 연산을 줄여 성능을 향상시킬 수 있다.
    Ex) skip, filter, distinct
List<String> names = Arrays.asList("Kim", "Lee", "Park", "Choi");

// 모든 요소가 map 메소드를 거친 후 skip 메소드를 만난다.
List<String> namesList1 = names.stream()
        .map(el -> {
            System.out.println("map() called, now element is " + el);
            return el.toUpperCase();
        })
        .skip(2)
        .collect(Collectors.toList());
       
System.out.println(namesList1);

// [실행 결과]
// map() called, now element is Kim
// map() called, now element is Lee
// map() called, now element is Park
// map() called, now element is Choi
// [PARK, CHOI]

 

List<String> names = Arrays.asList("Kim", "Lee", "Park", "Choi");

// 모든 요소가 skip 메소드를 거친 후 남은 요소가 map 메소드를 만난다.
List<String> namesList2 = names.stream()
        .skip(2)
        .map(el -> {
            System.out.println("map() called, now element is " + el);
            return el.toUpperCase();
        })
        .collect(Collectors.toList());
        
System.out.println(namesList2);

// [실행 결과]
// map() called, now element is Park
// map() called, now element is Choi
// [PARK, CHOI]

 

재사용

  • 종료 작업 시 스트림이 닫히므로 재사용이 불가능하다.
    스트림은 저장된 데이터를 꺼내서 처리하는 용도이며 데이터 저장 용도가 아니기 때문이다.
  • 데이터를 List에 저장 후 필요할 때마다 스트림을 생성하여 재사용할 수 있다.
List<String> namesList4 = Stream.of("Kim", "Lee", "Choi")
        .filter(el -> el.contains("i"))
        .collect(Collectors.toList());

namesList4.stream().forEach(System.out::println);
Optional<String> firstElement = namesList4.stream().findFirst();

 

지연 처리(Lazy Invocation)

  • 스트림의 최종 결과는 최종 작업이 이루어질 때 계산된다.

 

▷ 출처

https://futurecreator.github.io/2018/08/26/java-8-streams-advanced/

728x90

'Java' 카테고리의 다른 글

[자료 구조] 선형 구조(Linear Structure)  (0) 2024.07.24
Spring Framework의 주요 특징  (1) 2024.07.23
Stream(1)  (0) 2024.07.18
[Spring] @RequestBody vs @RequestParam  (0) 2024.07.10
[Spring] @Controller VS @RestController  (0) 2024.07.09