
다양한 데이터 소스(컬렉션, 배열)를 표준화된 방법으로 다루기 위한 것
stream.distinct().limit(5).sorted().forEach(System.out::println)
/* distinct() 중간 연산 - 중복 제거
limit(5) 중간 연산 - 5개 자르기
sorted() 중간 연산 - 정렬
forEach(System.out::println) 최종 연산 - 출력 */
String[] strArr = { "dd", "aaa", "CC", "cc", "b" };
Stream<String> stream = Stream.of(strArr); // 문자열 배열이 소스인 스트림
Stream<String> filteredStream = stream.filter(); // 걸러내기(중간 연산)
Stream<String> distinctedStream = stream.distinct(); // 중복제거(중간 연산)
Stream<String> limitedStream = stream.limit(5); // 스트림 자르기(중간 연산)
int total = stream.count(); // 요소 개수 \세기(최종연산)
List<Integer> list = Arrays.asList(3,1,5,4,2);
List<Integer> sortedList = list.stream().sorted().collect(Collectors.toList()); // list를 정렬해서 새로운 List에 저장
System.out.println(list); // [3,1,5,4,2]
System.out.println(sortedList); // [1,2,3,4,5]
strStream.forEach(System.out::println); // 모든 요소를 화면에 출력(forEach - 최종연산)
int numOfStr = strStream.count(); // 에러. 스트림이 이미 닫혔음. (count() - 최종연산)
최종 연산 전까지 중간연산이 수행되지 않는다. - 지연된 연산
스트림은 작업을 내부 반복으로 처리한다.
스트림의 작업을 병렬로 처리 - 병렬스트림
Stream<String> strStream - Stream.of("dd", "aaa", "CC", "cc", "b");
int sum = strStream.parallel() // 병렬 스트림으로 전환(속성만 변경)
.mapToInt(s->s.length()).sum(); // 모든 문자열의 길이의 합
Collection인터페이스의 stream()으로 컬렉션을 스트림으로 변환
Stream<E> stream() // Collection 인터페이스의 메서드
List<Integer> list = Arrays.asList(1,2,3,4,5);
Stream<Integer> intStream = list.stream(); // list를 스트림으로 변환
// 스트림의 모든 요소를 출력
intStream.forEach(System.out::print); // 12345
intStream.forEach(System.out::print); // 에러. 스트림이 이미 닫힘
Stream<T> Stream.of(T...values) // 가변 인자
Stream<T> Stream.of(T[])
Stream<T> Arrays.stream(T[])
Stream<T> Arrays.stream(T[] array, int startInclusive, int endExclusive)
IntStream IntStream.of(int... values) // Stream이 아니라 IntStream
IntStream IntStream.of(int[])
IntStream Arrays.stream(int[])
IntStream Arrays.stream(int[] array, int startInclusive, int endExclusive)
IntStreamintStream = new Random().ints(); // 무한 스트림
intStream.limit(5).forEach(System.out::println); // 5개의 요소만 출력한다.
IntStream intStream = new Random().ints(5); // 크기가 5인 난수 스트림을 반환