본문 바로가기
정리하기 이전 자료 ( before 20-11 )/Java

자바 8 Optional

by IMSfromSeoul 2020. 3. 11.

 

https://www.baeldung.com/java-8-new-features

 

New Features in Java 8 | Baeldung

A short intro into the new features of Java 8; the focus is on default and static interface methods, static method references, and Optional.

www.baeldung.com

 

Starting with Java 8, interfaces can have static and default methods that, despite being declared in an interface, have a defined behavior.

 

static String producer() {
    return "N&F Vehicles";
}

String producer = Vehicle.producer();

 자바8부터 interface의 static method를 바로 사용할 수 있게 됐다.

 

Optional<T>

 

Before Java 8 developers had to carefully validate values they referred to, because of a possibility of throwing the NullPointerException (NPE).

All these checks demanded a pretty annoying and error-prone boilerplate code.

Java 8 Optional<T> class can help to handle situations where there is a possibility of getting the NPE. It works as a container for the object of type T. 

It can return a value of this object if this value is not a null. When the value inside this container is null it allows doing some predefined actions instead of throwing NPE.

 

NullPointerException 을 피할 수 있는 방법으로 Optional이 등장했다.

 

Optional<String> optional = Optional.empty();

 

Optional 은 Optional 의 static method를 이용해서 만들 수 있다.

 

String str = "value";
Optional<String> optional = Optional.of(str);
System.out.println(optional);
출력결과 : Optional[value]

 

 

Optinal<T> Usage

 

List<String> list = getList();
List<String> listOpt = list != null ? list : new ArrayList<>();

List<String>을 불러오려면 null 때문에 null 체크를 꼭 해주어야 했다.

 

List<String> listOpt = getList().orElseGet(() -> new ArrayList<>());

Optinal을 이용하면 코드를 이렇게 한 줄로 줄일 수 있다.

 

User user = getUser();
if (user != null) {
    Address address = user.getAddress();
    if (address != null) {
        String street = address.getStreet();
        if (street != null) {
            return street;
        }
    }
}
return "not specified";

null 체크 때문에 모든 요소에 접근할 때 if( != null ) 을 사용해야 해서 가독성도 떨어지고 코드도 길어진다.

Optional<User> user = Optional.ofNullable(getUser());
String result = user
  .map(User::getAddress)
  .map(Address::getStreet)
  .orElse("not specified");

이런 문제를 이렇게 Optional 을 사용해서 해결할 수 있다.

'정리하기 이전 자료 ( before 20-11 ) > Java' 카테고리의 다른 글

배열 ( Array )  (0) 2020.03.27
Singleton Pattern  (0) 2020.03.25
Call by value VS Call by reference  (0) 2020.03.25
StringBuilder  (0) 2020.03.23
Buffered Reader/Writer  (0) 2020.03.16

댓글