Java Optional
- ๊ฐ์ด ์กด์ฌํ๊ฑฐ๋ ์กด์ฌํ์ง ์์ ์ ์๋ ์ํฉ์ ์์ ํ๊ฒ ์ฒ๋ฆฌํ๊ธฐ ์ํ ์ปจํ
์ด๋
์์ฑ
- Optional.of(T t)
- Optional.ofNullable(T t)
- Optional.empty()
๊ฐ ์ถ์ถ
- isPresent()
- orElse(T t)
- orElseGet(Supplier<? extends T> supplier)
- orElseThrow(Supplier<? extends X> exceptionSupplier)
- get()
๊ฐ ๋ณํ
- map(Function<? super T, ? extends U> mapper)
- flatMap(Function<? super T, Optional<? extends U>> mapper)
๊ฐ ๋น๊ต
- equals(Object obj)
- hashCode()
- toString()
์์
public class OptionalTest {
public static void main(String[] args) {
Optional<String> optional = Optional.of("Hello");
System.out.println(optional.get());
System.out.println(optional.orElse("World"));
System.out.println(optional.orElseGet(() -> "World"));
System.out.println(optional.orElseThrow(() -> new RuntimeException("No value present")));
System.out.println(optional.map(s -> s.toUpperCase()).orElse("World"));
System.out.println(optional.flatMap(s -> Optional.of(s.toUpperCase())).orElse("World"));
System.out.println(optional.equals(optional));
System.out.println(optional.equals(Optional.of("Hello")));
}
}
์ฐธ๊ณ