-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.java
More file actions
50 lines (39 loc) · 1.3 KB
/
App.java
File metadata and controls
50 lines (39 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package kr.springboot.examples.ex24;
import kr.springboot.examples.commons.Product;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
/**
* Do We Need to Chain the Optional API With the Stream API?
* 옵셔널 API랑 스트림 API의 연결이 필요할까?
*/
public class App {
public Optional<Product> fetchProductById(String id) {
Product product = new Product();
return Optional.ofNullable(product);
}
// Avoid
public List<Product> getProductListAvoid(List<String> productId) {
return productId.stream()
.map(this::fetchProductById)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());
}
/**
* Practically, Optional.stream() allows us to replace filter() and map() with flatMap().
*/
// Prefer
public List<Product> getProductListPrefer(List<String> productId) {
return productId.stream()
.map(this::fetchProductById)
.flatMap(Optional::stream)
.collect(toList());
}
/**
* Also, we can convertOptionalto List:
*/
public <T> List<T> convertOptionalToList(Optional<T> optional) {
return optional.stream().collect(toList());
}
}