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 |
import java.util.*; public class Main { public static void main(String[] args) throws Exception { Member taro = new Member("太郎", 31); Member hanako = new Member("花子"); System.out.println("taro : " + taro); System.out.println("hanako : " + hanako); } } class Member { private String name; private Optional<Integer> age; public Member(String name) { this.name = name; this.age = Optional.ofNullable(null); } public Member(String name, int age) { this.name = name; this.age = Optional.ofNullable(age); } public String getProfile() { return this.age .map(a -> String.format("%s(%d)", this.name, a)) .orElse(this.name); } @Override public String toString() { return this.getProfile(); } } |
1 2 |
taro : 太郎(31) hanako : 花子 |