스트림

윤휘영·2024년 12월 30일
0

람다식은 함수형 인터페이스를 구현한다.

1. 주요 인터페이스

1. 비교자(Comparator)

  • 함수형 인터페이스 Comparator<T>
  • 추상 메서드:
    int compare(T o1, T o2)
  • 비교자의 구현체로 T형 두 개를 받아 int를 반환하는 람다식이 가능.
Comparator<Integer> order = (a, b) -> a - b;

2. 조건자(Predicate)

  • 함수형 인터페이스 Predicate<T>
  • 추상 메서드:
    boolean test(T t)
  • 조건자의 구현체로 T형을 받아 boolean을 반환하는 람다식이 가능.
Predicate<Integer> isEven = x -> x % 2 == 0;

3. 소비자(Consumer)

  • 함수형 인터페이스 Consumer<T>
  • 추상 메서드:
    void accept(T t)
  • 소비자의 구현체로 T형을 받아 반환값 없이 처리하는 람다식이 가능.
Consumer<String> printer = s -> System.out.println(s);

4. 이진 연산자(BinaryOperator)

  • 함수형 인터페이스 BinaryOperator<T>
  • 추상 메서드:
    T apply(T t1, T t2)
  • 이진 연산자의 구현체로 T형 두 개를 받아 T형을 반환하는 람다식이 가능.
BinaryOperator<Integer> sum = (a, b) -> a + b;

5. 함수자(Function)

  • 함수형 인터페이스 Function<T, R>
  • 추상 메서드:
    R apply(T t)
  • 함수자의 구현체로 T형을 받아서 R형을 반환하는 람다식이 가능.
Function<String, Integer> f = s -> s.length();

6. 집계자(Collector)

  • 함수형 인터페이스가 아님.
  • 주요 메서드:
  1. toList(): 스트림의 모든 요소를 리스트로.
List<String> result = Stream.of("apple", "banana", "cherry")
                                    .collect(Collectors.toList());
        System.out.println(result); // [apple, banana, cherry]
  1. toSet(): 스트림의 모든 요소를 집합으로 수집.
Set<Integer> result = Stream.of(1, 2, 2, 3)
                             .collect(Collectors.toSet());
System.out.println(result); // [1, 2, 3]
  1. toMap(): 스트림의 요소를 키-값 쌍으로 수집.
Map<String, Integer> result = Stream.of("apple", "banana", "cherry")
                                            .collect(Collectors.toMap(
                                                fruit -> fruit,            // 키: 과일 이름
                                                fruit -> fruit.length())); // 값: 과일 이름의 길이
        System.out.println(result); // {apple=5, banana=6, cherry=6}
  1. joining(): 문자열 스트림을 하나의 문자열로.
String result = Stream.of("apple", "banana", "cherry")
                      .collect(Collectors.joining(", "));
System.out.println(result); // apple, banana, cherry
  1. counting(): 요소의 개수를 셈.
long count = Stream.of(1, 2, 3, 4)
                   .collect(Collectors.counting());
System.out.println(count); // 4
  1. groupingBy(): 키를 기준으로 그룹화.
Map<Integer, List<String>> result = Stream.of("apple", "banana", "cherry")
                                                  .collect(Collectors.groupingBy(String::length));
        System.out.println(result); // {5=[apple], 6=[banana, cherry]}

2. 주요 작업

1. 필터링

  • Stream distinct()
  • Stream filter(Predicate<T>)

2. 매핑

  • Stream<R> map(Function<T, R>)
    T형을 R형으로.
  • IntStream mapToInt(ToIntFunction<T>)
    T형을 int형으로.

3. 정렬

  • Stream<T> sorted()
    Comparable 원소를 정렬한 새 스트림 생성
  • Stream<T> sorted(Comparator<T>)
    원소를 비교자에 따라 정렬한 새 스트림 생성

4. 루핑

  • void forEach(Consumer<T>)
    T 반복

5. 매칭

  • boolean allMatch(Predicate<T> predicate)
    모든 요소가 만족하는지 여부

6. 집계

  • long count()
  • Optional<T> max(Comparator<T>)
  • OptionalXXX max()
  • Optional<T> min(Comparator<T>)
  • OptionalXXX min()
  • OptionalDouble average()
  • int, long, double sum()
  • Optional은 get(), OptionalXXX는 getAsDouble(), getAsInt(), getAsLong()으로 최종값을 얻음.

7. Optional 클래스의 메서드

  • boolean isPresent()
  • orElse(T)
    집계값이 없을 경우 디폴트값 설정
  • ifPresent(Consumer)
    집계값이 있을 경우 Consumer에서 처리

8. 원소 커스텀 집계

  • reduce(T identity, BinaryOperator<T> accumulator)
    스트림에 요소가 없을 경우 디폴트값 identity 반환

9. 최종 원소 수집

집계자 사용.

0개의 댓글