-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.java
More file actions
55 lines (43 loc) · 1.42 KB
/
App.java
File metadata and controls
55 lines (43 loc) · 1.42 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
51
52
53
54
55
package kr.springboot.examples.ex18;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* Avoid Using Optional in Collections
* 컬렉션에서 옵셔널을 사용하지 말것
*/
public class App {
// Avoid
public void avoidExample() {
Map<String, Optional<String>> items = new HashMap<>();
items.put("ITEM1", Optional.ofNullable(""));
items.put("ITEM2", Optional.ofNullable(""));
Optional<String> item = items.get("ITEM1");
if (item == null) {
System.out.println("이키로는 찾을 수 없다구");
} else {
String unwrappedItem = item.orElse("없어!!!!");
System.out.println("찾았다 : " + unwrappedItem);
}
}
// Prefer
public void preferExample() {
Map<String, String> items = new HashMap<>();
items.put("ITEM1", "Shoes");
items.put("ITEM2", null);
// 아이템 얻기
String item1 = get(items, "I1"); // Shoes
String item2 = get(items, "I2"); // null
String item3 = get(items, "I3"); // NOT FOUND
}
private String get(Map<String, String> map, String key) {
return map.getOrDefault(key, "찾았땅");
}
/**
* 그 외 다른 방법
* 1. containsKey() method
* 2. Trivial implementation by extending HashMap
* 3. Java 8computeIfAbsent() method
* 4. Apache Commons DefaultedMap
*/
}