본문
170420(목) - Streams <Laziness and Performance Optimization>
Programming/Java 8 2017. 4. 20. 13:55
Streams
- Laziness Improves Performance
ㆍBigger data & Infinite streams를 다루는 동안 쓰면 효율적이다.
ㆍlazy processing은 process only on demand strategy를 base로 하고있다.
- Laziness and Java 8 Streams
ㆍ사용자가 실제로 사용하기 전까지 collection operations를 하지 않는다.
//Created a Stream of a Students List
//attached a map operation on it
Stream<String> streamOfNames = students.stream()
.map(student -> {
System.out.println("In Map - " + student.getName());
return student.getName();
});
//Just to add some delay
for (int i = 1; i <= 5; i++) {
Thread.sleep(1000);
System.out.println(i + " sec");
}
//Called a terminal operation on the stream
streamOfNames.collect(Collectors.toList());
Output:
1 sec
2 sec
3 sec
4 sec
5 sec
In Map - Tom
In Map - Chris
In Map - Dave
- Performance Optimization
various intermediate operations pipe를 만들고, terminal operations로 마무리한다.
List<String> ids = students.stream()
.filter(s -> {System.out.println("filter - "+s); return s.getAge() > 20;})
.map(s -> {System.out.println("map - "+s); return s.getName();})
.limit(3)
.collect(Collectors.toList());
Output:
filter - 8
map - 8
filter - 9
map - 9
filter - 10 // didn't pass filter test
filter - 11
map - 11
- Short Circuit Methods
ㆍshort circuit 을 통해서 streams 처리를 최적화 한다.
조건이 만족되는 스트림을 조기 종료처리 해버림
//List of names
List<String> names = Arrays.asList(new String[]{"barry", " andy", "ben", "chris", "bill"});
//map and filter are piped and the stream is stored
Stream<String> namesStream = names.stream()
.map(n -> {System.out.println("In map - " + n); return n.toUpperCase();})
.filter(upperName -> {System.out.println("In filter - " + upperName);
return upperName.startsWith("B");});
'Programming > Java 8' 카테고리의 다른 글
170420(목) - Streams <Terminal Operations> (0) | 2017.04.20 |
---|---|
170420(목) - Streams <Intermediate Operations> (0) | 2017.04.20 |
170420(목) - Streams <Understanding Java 8 Streams API (0) | 2017.04.20 |
170419(수) - Lambda Expressions (0) | 2017.04.19 |
170419(수) - Default Methods (0) | 2017.04.19 |
댓글