Stream

GILHUN·2022년 10월 18일
0

개요

Stream : 다양한 데이터 소스를 표준화된 방법으로 다루기 위한 것
제공기능 : 중간연산, 최종연산
특징
-데이터를 읽기만할 뿐 변경하지 않는다.
-일회용이다.(필요하면 다시 스트림 생성해야함 - Iterator와 비슷)
-최종연산 전까지 중간연산이 수행되지 않는다.(지연된 연산)
-스트림은 작업을 내부 반복으로 처리한다.

Method

1. 중간연산

가. 스트림 자르기 - skip(), limit()

Stream<T> skip(long n) // 앞에서부터 n개 건너뛰기
Stream<T> limit(long maxSize) // maxSize 이후의 요소는 잘라냄
IntStream intStream = IntStream.rangeClosed(1,10); // 12345678910
intStream.skip(3).limit(5).forEach(System.out::print); // 45678

나. 스트림의 요소 걸러내기 - filter(), distinct()

2. 최종연산

가. 스트림의 모든 요소에 지정된 작업 수행 - forEach(), forEachOrdered()

void forEach(Consumer<? super T> action) // 병렬스트림 경우 순서 보장 X
void forEachOrdered(Consumer<? super T> action) // 병렬스트림 경우도 순서 보장
IntStream.range(1,10).sequential().forEach(System.out::print); // 123456789
IntStream.range(1,10).sequential().forEachOrdered(System.out::print); // 123456789
IntStream.range(1,10).parallel().forEach(System.out::print); // 683295714
IntStream.range(1,10).parallel().forEachOrdered(System.out::print); // 123456789

나. 스트림->배열 - toArray()

Object[] toArray() // 스트림의 모든 요소 Object배열에 담아 반환
A[]      toArray(IntFunction<A[]> generator) // 스트림의 모든 요소 A타입의 배열에 담아 반환
Student[] stuName = studentStream.toArray(Student[]::new); // OK
Student[] stuName = studentStream.toArray(); // 에러
Object[]  stuName = studentStream.toArray(); // Ok

다. 조건 검사 - allMatch(), anyMatch(), noneMatch()

profile
기록하고 정렬하고 성장하자

0개의 댓글