<aside>
컬렉션(Collection), 배열, I/O 채널 등의 데이터를 함수형 스타일로 처리하기 위한 추상화된 도구
데이터가 저장된 구조(예: List
, Set
)와는 분리되어, 데이터를 순차적 또는 병렬적으로 처리할 수 있는 일종의 '데이터 처리 파이프라인'을 제공
stream()
은 다시 만들어야 함collect
, forEach
)이 있어야 실행됨filter
– 조건에 맞는 것만 통과시킴List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);
nums.stream()
.filter(n -> n % 2 == 0) // 짝수만 남김
.forEach(System.out::println); // 출력
// 결과: 2 4
map
– 데이터를 변형함List<String> words = Arrays.asList("java", "spring", "boot");
words.stream()
.map(word -> word.toUpperCase()) // 대문자로 변환
.forEach(System.out::println);
// 결과: JAVA SPRING BOOT
collect
– 결과를 다시 List, Set 등으로 저장List<String> names = Arrays.asList("Kim", "Lee", "Park");
List<String> upperNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upperNames); // [KIM, LEE, PARK]
count
– 요소 개수 세기long count = Stream.of("apple", "banana", "apricot")
.filter(f -> f.startsWith("a"))
.count();
System.out.println(count); // 2 (apple, apricot)