
[ Stream ]
사전적 의미로는 개울, 줄지어가다 등이있다.
그렇다면, 자바에서 Stream은 무엇일까?
자바 8버전에서 새로 추가된 기능이다. 스트림을 이용하면 선언형으로 컬렉션 데이터를 처리할 수 있다. 쉽게 말해 데이터를 쉽게 다루기 위한 도구이다. 데이터를 목록(리스트), 배열 같은 형태로 저장하는데, 이런 데이터를 "한 줄로 흐르는 강물처럼" 처리하는 방법이다.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<String> filteredNames = new ArrayList<>();
for (String name : names) {
if (name.startsWith("A")) { // "A"로 시작하는 이름만 골라내기
filteredNames.add(name);
}
}
System.out.println(filteredNames); // [Alice]
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<String> filteredNames = names.stream()
// 데이터를 스트림으로 변환
.filter(name -> name.startsWith("A")) // 필터링
.toList();
// 리스트로 결과 만들기
System.out.println(filteredNames); // [Alice]
4명의 이름중 A로 시작하는 이름만 골라내는 두개의 코드.
데이터를 스트림으로 변환.
List<String> list = Arrays.asList("A", "B", "C");
Stream<String> stream = list.stream();
데이터를 걸러내거나 바꾸는 작업.
names.stream()
.filter(name -> name.startsWith("A")) // "A"로 시작하는 데이터만
.map(name -> name.toUpperCase()); // 대문자로 변환
결과를 만드는 작업.
names.stream()
.filter(name -> name.startsWith("A"))
.forEach(System.out::println); // 결과 출력