Last active
August 29, 2015 14:04
-
-
Save kazu-yamamoto/db10dd7600653109b57a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
class Person { | |
String name; | |
int age; | |
Person (String n, int a) { | |
name = n; | |
age = a; | |
} | |
} | |
public class OptHashMap<K,V> extends HashMap<K,V> { | |
// HashMap get() のラッパー | |
public Optional<V> search(K key) { | |
return Optional.ofNullable(get(key)); | |
} | |
public static void main (String[] args) { | |
OptHashMap<String,Person> db = new OptHashMap<String,Person>(); | |
// 親子 DB の初期化 | |
Person sazae = new Person("サザエ", 24); | |
Person fune = new Person("フネ", 52); | |
db.put("タラオ",sazae); | |
db.put("サザエ",fune); | |
// フネのお母さんは死んでいる | |
// flatMap を使って、エラー処理を地下配線にする | |
// タラちゃんのひいおばあちゃんはいるか? | |
String me = "タラオ"; | |
Optional<Person> ggrammer = db.search(me).flatMap( | |
mother -> db.search(mother.name)).flatMap( | |
gmother -> db.search(gmother.name)); | |
// 結果を表示 | |
if (ggrammer.isPresent()) { | |
System.out.println(ggrammer.get().name); | |
} else { | |
System.out.println("いません"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment