자바 8 에서 추가한 스트림은 람다를 활용할 수 있는 기술 중 하나이다.
스트림은 '데이터의 흐름'이다. 배열 또는 컬렉션의 인스턴스에 함수 여러 개를 조합해서
원하는 결과를 필터링하고 가공된 결과를 얻을 수 있다. 또한 람다를 이용해서 코드의 양을 줄이고
간결하게 표현할 수 있다. 즉, 배열과 컬렉션을 함수형으로 처리할 수 있다.
1.생성하기 ( Array, Collection )
2.가공하기 ( Filter , Map , Sort , Distinct 등등 )
3.결과만들기 ( 최대-최소-평균 연산 , 합-카운트 , 데이터 수집 연산(collect) 처리 , 특정 조건 검사 , 반복문 )
전체 -> 맵핑 -> 필터링1 -> 필터링2 -> 결과만들기 -> 결과물
( 컬렉션 스트림 생성 )
( 배열 스트림 생성 )
( 객체 배열 스트림 생성 )
( 람다식 iteratio(), generate(); )
void forEach(Consumer<? super T> action) //각 요소에 지정된 작업 수행
void forEachOrdered(Consumer<? super T> action) //병렬 스트림의 경우 순서를 유지하며 수행
long count() //스트림의 요소 개수 반환
Optional max(Comparator<? super T> comparator) //스트림의 최대값 반환
Optional min(Comparator<? super T> comparator) //스트림의 최소값 반환
Optional findAny() //아무거나 하나 반환. 벙렬 스트림에 사용
Optional findFirst() //첫 번째 요소 반환. 순차 스트림에 사용
boolean allMatch(Predicate p) //모든 조건을 만족?
boolean anyMatch(Predicate p) //조건을 하나라도 만족?
boolean noneMatch(Predicate p) //모든 조건을 만족하지 않음?
Object[] toArray() //모든 요소를 배열로 반환
A[] toArray(IntFunction<A[]> generator) //특정 타입의 배열로 반환
Optional reduce(BinaryOperator accumulator) //스트림의 요소를 하나씩 줄여가면서 계산
collect( ~ ) //데이터를 변형 등의 처리를 하고 원하는 자료형으로 변환해 줍니다.
1.Filter
classes.stream()
.filter(c->c.getTitle().startWith("spring"))
.forEach(c->System.out.println(oc.getId));
2.Map 또는 FlatMap
map(File::getName) //각각의 File에서 String name만 새로운 스트림으로
map(s->s.subString(3)) //string 타입 요소를 짤라서 새로운 스트림으로
3.limit(long) 또는 skip(long)
Stream.iterate(10, i->i+1)
.skip(10)
.limit(10)
.forEach(System.out::println)
4.anyMatch(), allMatch(), nonMatch()
boolean test=javaClasses.stream()
.anyMatch(oc->oc.getTitle().contains("k"));
5.findFirst() VS findAny()
6.reduce()
Integer sum = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).reduce((total, y) -> total + y);
System.out.println("sum: " + s); //sum: 55
//초기값을 지정해 줄 수 있다.
Integer sum = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).reduce(10, (total, n) -> total + n);
System.out.println("sum: " + sum); //sum: 65
7.collect()
stream.collect(Collectors.toSet()); //set으로 변환
stream.collect(Collectors.toList()); //list 변환
stream.collect(Collectors.joining()); //한개의 string으로 변환
stream.collect(Collectors.joining(", ")); //요소들 사이에 ","을 넣어서 한개의 string 반환
8.간단 예제
IntStream.range(1, 11).filter(i-> i%2==0)
.forEach(System.out::println); //같은 뜻
.forEach(i->System.out.println(i)); //같은 뜻
9.간단 예제
System.out.println(
IntStream.range(0, 1001)
.skip(500)
.filter(i-> i%2==0)
.filter(i-> i%5==0)
.sum()
);