> For the complete documentation index, see [llms.txt](https://organization-bht.gitbook.io/it/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://organization-bht.gitbook.io/it/undefined/java/16-lamda/3.-api-stream-api.md). Agents can also search and read this documentation through its [MCP server](https://organization-bht.gitbook.io/it/~gitbook/mcp).

# 3. 스트림 API (Stream API)

스트림(Stream)은 자바 8에 도입된 기능으로, **컬렉션 데이터를  람다 표현식을 활용해 함수형 스타일로 처리**할 수 있도록 도와줍니다. `filter`, `map`, `collect` 등 다양한 메서드를 조합해 데이터 흐름을 **파이프라인** 형태로 다룰 수 있습니다.

***

### 스트림

<figure><img src="https://3572862491-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FUON3CGxVeoUR2YdtAhxl%2Fuploads%2F263QMimY1Mt8ay6iJ8SR%2F%EC%8A%A4%ED%8A%B8%EB%A6%BC.png?alt=media&amp;token=54b13d9c-1d2f-426e-a79b-a5f0478aac97" alt=""><figcaption></figcaption></figure>

* Stream은 **데이터의 흐름을 표현하는 추상화된 개념**이며, 내부 반복을 통해 데이터를 처리합니다.
* Stream은 데이터를 다루기 위한 **중간 연산** 여러개와 **최종 연산** 1개가 존재합니다.
* Stream의 메서드들은 최종 연산메서드가 실행되기 전까지 **지연 연산**(Lazy Evaluation) 됩니다.
* Stream의 최종 연산 완료 후 원본 컬렉션,배열 **데이터는 변경되지 않습**니다.
* Stream은 재사용이 불가능합니다.

***

### 기본 사용 예제

```
List<String> names = Arrays.asList("Java", "Kotlin", "Scala", "Python");

names.stream()
     .filter(s -> s.length() > 4)
     .map(String::toUpperCase)
     .forEach(System.out::println);
```

***

### 주요 메서드 정리

| 메서드                   | 설명            |
| --------------------- | ------------- |
| `filter(Predicate)`   | 조건에 맞는 요소만 통과 |
| `map(Function)`       | 요소 변환         |
| `flatMap(Function)`   | 중첩된 스트림을 평면화  |
| `forEach(Consumer)`   | 각 요소에 대해 실행   |
| `collect(Collectors)` | 결과 수집 (리스트 등) |
| `sorted()`            | 정렬            |
| `distinct()`          | 중복 제거         |
| `limit(n)`            | 앞에서 n개 요소 제한  |
| `count()`             | 요소 개수 반환      |

***
