![](https://velog.velcdn.com/images/mpfo0106/post/10baaf35-3c46-4f5d-b8b1-d6d35b61183b/image.png)
중간연산
기본 유형 => 래퍼 객체 스트림 변환
스트림 요소 걸러내기
중복제거
요소 제외
IntStream intStream = IntStream.rangeClosed(1,10);
intStream.filter(i -> i%2 == 0).forEach(System.out::print);
스트림 자르기
일부 잘라내기
일부 건너뛰기
IntStream intStream = IntStream.rangeClosed(1,10);
intStream.skip(3).limit(5).forEach(System.out::print);
스트림 정렬
요소 정렬 sorted
strStream.sorted()
strStream.sorted(Comparator.reverseOrder())
Stream<String> stringStream = Stream.of("dd", "aaa", "CC", "cc", "b");
stringStream.sorted().forEach(System.out::print);
Stream<String> stringStream2 = Stream.of("dd", "aaa", "CC", "cc", "b");
stringStream2.sorted(Comparator.reverseOrder()).forEach(System.out::print);
요소에 작업수행
요소 변환 map()
map()
mapToInt, mapToLong, mapToDouble
- 그렇기에 각각 IntStream 사용을 추천!
- IntStream 은 sum(), average(),max(),min() 등을 제공 (얘네는 최종연산)
Stream<Student> studentStream = Stream.of(
new Student("이자바", 3, 300),
new Student("이", 3, 300),
new Student("자", 1, 200),
new Student("바", 3, 100),
new Student("이자", 3, 300)
);
IntStream studentScoreStream = studentStream.mapToInt(Student::getTotalScore);
int allTotalScore = studentScoreStream.sum();
System.out.println(allTotalScore);
flatMap
Stream<T[]> => Stream<T> 로 변환
- flatMapToDouble
- flatMapToInt
- flatMapToLong
최종연산
- 연산. 스트림의 요소를 소모함으로 단 한번만 가능
요소 출력
- forEach X => .collect(Collectors.toList()) 를 사용하자.
조건 검사
allMatch
anyMatch
noneMatch
findAny
findFirst
- 조건 맞는 첫번째
- filter랑 짝궁
- Optional 반환
통계
count , max, min // sum, average => IntStream
요소를 줄이면서(reduce) 계산
reduce
T reduce(T identity, BinaryOperator<T> accumulator)
- accumulator: 두 개의 매개변수를 취하고 하나를 반환하는 BinaryOperator 입니다.
- 스트림 요소를 결합하기 위해 반복적으로 적용됩니다.
import java.util.Arrays;
import java.util.List;
public class ReduceExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (total, number) -> total + number);
System.out.println("Sum is: " + sum);
}
}
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class ReduceExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> max = numbers.stream()
.reduce((a, b) -> a > b ? a : b);
max.ifPresent(m -> System.out.println("Maximum is: " + m));
}
}
- 초기값('identity')은 '0'입니다.
- accumulator는 람다 함수 (total, number) -> total + number입니다. 현재 총계와 스트림의 현재 숫자라는 두 가지 매개변수를 사용합니다. 업데이트된 합계를 반환합니다.
collect
toList, toSet, toMap, toCollection,toArray
toList
List<String> names = studentStream.map(Student::getName)
.collect(Collectors.toList());
Stream.of(names).forEach(System.out::println);
스트림 만들기
컬렉션
Stream<T> Collection.stream()
List<Integer> list = Arrays.asList(1,2,3,4,5)
Stream<Integer> intSteram = list.stream();
Optional
String str = "abc";
Optional<String> optVal = Optional.of(str);
Optional<String> optVal2 = Optional.of(null);
Optional<String> optVal3 = Optional.ofNullable(null);