> For the complete documentation index, see [llms.txt](https://5color.gitbook.io/dee/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://5color.gitbook.io/dee/temp/page/untitled-1.md).

# Java Stream

## Stream - 생성 / 가공 / **Terminal Operations**

{% embed url="<https://futurecreator.github.io/2018/08/26/java-8-streams/>" %}

* 배열과 컬렉션을 함수형으로 처리할 수 있다
* 병렬처리(*multi-threading*)가 가능하다
* 재사용은 불가능하다

**\*\* 생성**

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

#### *Stream.iterate()* <a href="#stream-iterate" id="stream-iterate"></a>

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

#### \*\* 가공 (중개 연산)  <a href="#filtering" id="filtering"></a>

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

#### filter, map <a href="#filtering" id="filtering"></a>

#### flatmap <a href="#mapping" id="mapping"></a>

```bash
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
```

```bash
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 <a href="#mapping" id="mapping"></a>

```
// 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  <a href="#reduction" id="reduction"></a>

### \*\* Null-safe  <a href="#null-safe" id="null-safe"></a>

```bash
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); // []
```

## 불변 컬렉션&#x20;

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

```bash
import com.google.common.collect.ImmutableList;

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

fruits.add("Lemon"); // UnsupportedOperationException
```

* Java 9 에서는 of 메소드 제공
