hoonii2

[Java] 08. Stream 본문

개념 공부/(개발) 01. Java

[Java] 08. Stream

hoonii2 2023. 1. 6. 18:16

1. 개요

자바 8 에서추가된 Stream 은 람다를 활용하여 이용하는 인터페이스이다.

특정 배열이나 자료구조를 다루기위해 for / foreach 를 사용했었지만 반복문 내부에 로직이 복잡해지면 여러 로직이 섞이고 최악의 경우 내부 로직에서 배열이나 자료구조의 데이터를 변경하는 등의 작업이 섞일 수 있다.

 

스트림은 데이터를 필터링하여 가공된 결과를 얻을 수 있으며, 내부적으로 데이터의 변환이 발생할 수 없도록 동작하여 안전하게 이용할 수 있다.

또한 병렬처리가 가능하여 쓰레드를 이용하여 많은 요소를 빠르게 처리할 수 있다.

 

 

좀 더 자세한 사항들은 Oracle Doc 에서 확인할 수 있다.

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

 

Stream (Java Platform SE 8 )

A sequence of elements supporting sequential and parallel aggregate operations. The following example illustrates an aggregate operation using Stream and IntStream: int sum = widgets.stream() .filter(w -> w.getColor() == RED) .mapToInt(w -> w.getWeight())

docs.oracle.com

 

 

2. 스트림 동작

 - 생성 : Stream Instance 생성

 - 가공 : Filtering / Mapping 을 통해 결과를 도출

 - 완성 : 가공된 결과를 최종 값으로 생성

 

 

3. 생성

  1) 배열 스트림

    : Arrays.stream 메소트 활용

String[] arr = new String[]{"a", "b", "c"};
Stream<String> stream = Arrays.stream(arr);


  2) 컬렉션 스트림

    : Collection 타입 인터페이스에 아래의 디폴트 메소드가 추가되어서 이를 활용하여 Stream 을 만들 수 있다.

public interface Collection<E> extends Iterable<E> {
  default Stream<E> stream() {
    return StreamSupport.stream(spliterator(), false);
  } 
  // ...
}

    : 아래의 활용 예시

List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();

 

  3) 비어있는 스트림

    : Empty Stream 도 만들 수 있는데, 요소가 없는 경우 'null' 대신 사용할 수 있다.

public Stream<String> streamOf(List<String> list) {
  return list == null || list.isEmpty() ? Stream.empty() : list.stream();
}

 

  4) Stream.Builder

    : 빌더를 통해 직정 값을 넣어 스트림을 만들 수 있다.

Stream<String> builderStream = 
  Stream.<String>builder()
    .add("a").add("b").add("c")
    .build(); // [a, b, c]

 

  5) Stream.generate

    : generate 메소드를 통해 'Supplier<T>' 에 람다로 값을 넣을 수 있다. ( Supplier 는 인자는 없고 리턴만 있는 함수형 인터페이스 )
    : 단 이 때 스트림은 크기가 무한해서 특정 사이즈로 제한을 걸어야 한다.

public static<T> Stream<T> generate(Supplier<T> s) { ... }

// 크기 제한
Stream<String> generatedStream = 
  Stream.generate(() -> "test").limit(5);

    : "test" 가 5개인 스트림

 

  6) Stream.iterate

    : 초기값과 이를 다루는 람다를 통해 스트림 요소를 생성할 수 있다.

Stream<Integer> iteratedStream = 
  Stream.iterate(15, n -> n + 5).limit(4); // [15, 20, 25, 30]

 

Comments