[자바 코테] Stream 정리

Update:     Updated:

카테고리:

태그:

Stream의 종류

구글링하다보면 같은 동작인데 방법이 너무 많다. 이 기회에 정리해보자..

Stream<T>: 제네릭 기반으로 정의됨
IntStream, LongStream, DoubleStream 등등: 기본 자료형 기반

Stream을 생성하는 법

  1. 배열: Arrays 클래스의 static 메소드인 stream()에 배열 인스턴스를 전달한다.

     int[] i = {1,2,3,4,5};
     IntStream istm = Arrays.stream(i);
        
     Integer[] i = {1,2,3,4,5};
     Stream<Integer> istm = Arrays.stream(i);
    
  2. 컬렉션: 컬렉션 인스턴스를 대상으로 디폴트 메소드 stream()을 호출함.

     List<String> s = Arrays.asList("a", "b", "c");
     Stream<String> sstm = s.stream();
    
  3. 데이터 직접 전달: Stream클래스 혹은 IntStream 등의 기본 자료형 스트림의 static 메소드인 of()에 stream에 넣고 싶은 데이터들을 전달한다.

     Stream<Integer> istm = Stream.of(1,2,3);
     IntStream istm = IntStream.of(1,2,3);
    

중간 연산(Intermediate Operation)의 종류

여러가지 있겠지만 대표적인 것들만 파악해보자..!

java에 이미 정의되어있는 인터페이스의 종류(Predicate, Consumer, Function, Supplier 등등)를 미리 알아둔다면 각 메소드의 의미를 해석하는데 좀 더 도움이 된다.
잘 모르겠다면 람다를 열심히 공부하자..

  1. filter(Predicate<T> p): boolean test(T t)를 구현할 것!
  2. map(Function<T, R> f): R apply(T t)를 구현할 것!
    1. mapToInt: int applyAsInt(T t)를 구현할 것!
    2. flatMap(Function<T, Stream<R>> f): Stream을 리턴한다.
  3. peek(consumer<T> c): void accept(T t)를 구현할 것!
    1. forEach()와 같지만 중간 연산이라는 차이점이 있다.
  4. sorted(Comparator<T> c): int compare(T o1, T o2)를 구현할 것!

최종 연산(Terminal Operation)의 종류

  1. forEach(Consumer<T> c): void accept(T t) 를 구현할 것!
  2. toArray()
  3. collect(): 주로 Collectors 클래스의 static 메소드와 같이 쓴다.
    1. collect(Collectors.toList()): 리스트로 만들 때 유용함.
    2. collect(Collectors.joining(””)): string으로 만들 때 유용함.
  4. sum(), count(), average(), min(), max()
    1. IntStream, LongStream, DoubleStream 인스턴스 대상으로만 사용이 가능하다.
    2. average(), min(), max() 메소드들은 결과값으로 Optional 인스턴스가 나오니, ifPresent(Consumer<T> c), get(), orElse() 등의 메소드들을 사용해주면 된다.
  5. allMatch(), anyMatch(), noneMatch()

Java Coding Test 카테고리 내 다른 글 보러가기

댓글 남기기