[기술정리] Stream API

Stupefyee's avatar
Nov 20, 2024
[기술정리] Stream API

1. 개념

  • Stream
    • 데이터의 집합을 처리하는
    • 추상화된 방식
    • 데이터 처리 파이프라인
  • 추상적 정리
어부가 통발(Collection)에 여러 물고기(elem)을 가지고 있을 때, 강에 물고기들을 뿌리고(stream), 강의 시작점부터 마지막까지 훑어 보며 작업하는 것.

2. 사용법

1. 개요

  • 컬렉션
    • List, Set, Map 등
  • stream()
    • 컬렉션에서 호출
    • 데이터 흐름 생성
  • 중간 연산
    • map(), filter(), sorted() 등
    • 지연 평가 (Lazy Evaluation)
  • 최종 연산
    • forEach(), collect(), count() 등
    • 결과 생산

2. Stream 중간 연산

  • filter()
    • 조건에 맞는 데이터 필터링
    • 예: 짝수만 필터링
  • map()
    • 데이터 변환
    • 예: 숫자를 제곱
  • sorted()
    • 데이터 정렬
    • 기본: 오름차순
  • distinct()
    • 중복 제거
  • groupingBy()
    • 주어진 조건에 따라 데이터를 그룹화
    • 예: 첫 번째 글자별로 문자열 그룹화

3. Stream 최종 연산

  • forEach()
    • 각 요소에 대한 동작 수행
    • 예: 출력, 변경
  • collect()
    • 스트림을 컬렉션으로 변환
    • 예: List, Set
  • count()
    • 요소 개수 세기
  • reduce()
    • 요소들을 결합
    • 예: 합계, 평균 등

4. 예시 코드

  • count()
import java.util.Arrays; import java.util.List; public class CountApp { public static void main(String[] args) { // 1. count List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David"); List<String> r1 = names.stream() .filter(name -> name.length() > 3) .toList(); r1.forEach(s -> System.out.println(s)); long r2 = names.stream() .filter(name -> name.length() > 3) .count(); System.out.println(r2); } }
  • map()
import java.util.Arrays; import java.util.List; public class MapApp { public static void main(String[] args) { // 2. map (가공) List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David"); List<String> newNames = names.stream() .map(name -> name.toLowerCase()) .filter(name -> name.length() > 3) .toList(); newNames.forEach(name -> System.out.println(name)); } }
  • reduce()
import java.util.Arrays; import java.util.List; public class ReduceApp { public static void main(String[] args) { // 3. reduce (조인) List<Integer> nums = Arrays.asList(1, 2, 3, 4); int sum = nums.stream() .mapToInt(x -> x) .sum(); System.out.println("배열의 합: " + sum); Integer sum2 = nums.stream() .reduce(5, (prev, next) -> { System.out.println("prev: " + prev); System.out.println("next: " + next); System.out.println("========"); return prev + next; }); System.out.println(sum2); } }
  • sorted()
import java.util.Arrays; import java.util.List; public class SortApp { public static void main(String[] args) { // 4. sort, distinct (정렬, 중복제거) List<Integer> nums = Arrays.asList(5, 3, 1, 2, 4, 5, 2); nums.stream() .sorted() .distinct() .forEach(integer -> System.out.println(integer)); } }
  • groupingBy()
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class GroupApp { public static void main(String[] args) { // 5. group List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "anna"); // Map<Character, List<String>> var groupData = names.stream() .map(name -> name.toUpperCase()) .collect(Collectors.groupingBy(s -> s.charAt(0))); System.out.println(groupData); System.out.println(groupData.get('A')); } }

3. 장점

  • 간결함
    • 선언적 프로그래밍
  • 병렬 처리
    • 멀티코어 CPU 활용 가능
  • 가독성
    • 코드 간결하고 명확

4. 단점

  • 성능
    • 작은 데이터에선 성능 저하 가능
  • 디버깅 어려움
    • 파이프라인 방식으로 흐름 추적 어려움
Share article

stupefyee