Java Stream

Stream - 생성 / 가공 / Terminal Operations

  • 배열과 컬렉션을 함수형으로 처리할 수 있다

  • 병렬처리(multi-threading)가 가능하다

  • 재사용은 불가능하다

** 생성

List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
Stream<String> parallelStream = list.parallelStream(); // 병렬 처리 스트림

Stream.iterate()

Stream<Integer> iteratedStream = 
  Stream.iterate(30, n -> n + 2).limit(5); // [30, 32, 34, 36, 38]

** 가공 (중개 연산)

List<String> names = Arrays.asList("Eric", "Elena", "Java");

filter, map

flatmap

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
List<List<String>> list = 
  Arrays.asList(Arrays.asList("a"), 
                Arrays.asList("b"));  // [[a], [b]]
                
                
List<String> flatList = 
  list.stream()
  .flatMap(Collection::stream)
  .collect(Collectors.toList());   // [a, b]
  
  
// if students  
students.stream()
  .flatMapToInt(student -> 
                IntStream.of(student.getKor(), 
                             student.getEng(), 
                             student.getMath()))
  .average().ifPresent(avg -> 
                       System.out.println(Math.round(avg * 10)/10.0));  
                

peek

// Stream<T> peek(Consumer<? super T> action);

int sum = IntStream.of(1, 3, 5, 7, 9)
  .peek(System.out::println) // 1, 3, 5, 7, 9
  .sum();  // sun = 25

** Terminal Operations (최종 연산)

reduce, collect

** Null-safe

public <T> Stream<T> collectionToStream(Collection<T> collection) {
    return Optional
      .ofNullable(collection)
      .map(Collection::stream)
      .orElseGet(Stream::empty);
  }
  
  
List<String> nullList = null;

nullList.stream()
  .filter(str -> str.contains("a"))
  .map(String::length)
  .forEach(System.out::println); // NPE!


collectionToStream(nullList)
  .filter(str -> str.contains("a"))
  .map(String::length)
  .forEach(System.out::println); // []

불변 컬렉션

Guava는 불변 리스트 생성을 위 팩토리 메서드나 빌더 클래스를 제공합니다.

import com.google.common.collect.ImmutableList;

List<String> fruits = ImmutableList.of("Apple", "Banana", "Cherry");

fruits.add("Lemon"); // UnsupportedOperationException
  • Java 9 에서는 of 메소드 제공

Last updated

Was this helpful?