본문
170420(목) - Streams <Terminal Operations>
Programming/Java 8 2017. 4. 20. 15:47
Streams
- Matching
- At least one element matches to the predicate
//Check if at least one student has got distinction
Boolean hasStudentWithDistinction = students.stream()
.anyMatch(student -> student.getScore() > 80);
- All element match to the predicate
//Check if All of the students have distinction
Boolean hasAllStudentsWithDistinction = students.stream()
.allMatch(student -> student.getScore() > 80);
- None of the elements matches to the predicate
//Return true if None of the students are over distinction
Boolean hasAllStudentsBelowDistinction = students.stream()
.noneMatch(student -> student.getScore() > 80);
- Finding
//Returns any student that matches to the given condition
students.stream().filter(student -> student.getAge() > 20)
.findAny();
//Returns first student that matches to the given condition
students.stream().filter(student -> student.getAge() > 20)
.findFirst();
- Reducing
ㆍ하나의 element 형태로 출력을 생성하기 위해서 streams내의 element를 반복하여 처리
ㆍ모든 요소의 합, 최대 최소 element 계산 등에 유리
ㆍ함수형 언어의 fold 개념과 비슷하다.
- Summing and Multiplying
//Summing all elements of a stream
Integer sum = numbers.stream()
.reduce(0, (x, y) -> x + y); //reduce(identity, accumulator)
//Product of all elements in a stream
Integer product = numbers.stream()
.reduce(1, (x, y) -> x * y);
//Summing without passing an identity
Optional<integer> sum = numbers.stream()
.reduce((x, y) -> x + y);
//Product without passing an identity
Optional<integer> product = numbers.stream()
.reduce((x, y) -> x * y);
- Min and Max
//Min of the stream
Optional<integer> min = numbers.stream()
.reduce(0, Integer::min);
//Max of the stream
Optional<integer> max = numbers.stream()
.reduce(0, Integer::max);
- Optional
ㆍ객체가 할당되었는지, 할당 해제되었는지 나타냄 : Null 반환에 대한 대비책
ㆍfindAny() 에서 Optional 반환 -> map은 Optional instance에서 호출된다.
students.stream()
.filter(student -> student.getScore() > 80) // filter
.findAny() //Any student matching to the filter
.map(Student::getName) // mapping to students name
.ifPresent(System.out::println); // print if name of the student is not Null
'Programming > Java 8' 카테고리의 다른 글
170427(목) - Method References (0) | 2017.04.27 |
---|---|
170427(목) - Repeating Annotations (0) | 2017.04.27 |
170420(목) - Streams <Intermediate Operations> (0) | 2017.04.20 |
170420(목) - Streams <Laziness and Performance Optimization> (0) | 2017.04.20 |
170420(목) - Streams <Understanding Java 8 Streams API (0) | 2017.04.20 |
댓글