Optional 클래스
옵셔널박스에 객체 담기
Optional<타입> 이름 = Optional.of(객체명);
: 들어가는 객체가 무조건 not null
Optional<타입> 이름 = Optional.ofNullable(객체명);
: null도 넣을 수 있음
+
int데이터를 넣을 경우
Optional<Int>는 없기 때문에
Integer로 만들어져서 성능저하를 일으킴
OptionalInt
OptionalDouble
로 만들어주면 됨
Optional 클래스의 메소드
isPresent()
: 데이터가 존재하는지 true false
ifPresent()
: 만약 옵셔널박스의 데이터가 null이 아니면 ()안의 매개변수가 실행됨
매개변수로 함수형 인터페이스 Consumer<>이 들어감!!
그래서 리턴타입 없음
이 코드를 더 줄이면
메소드 참조를 사용해서 코드를 더 줄일 수 있음...!
map()
map은 Optional박스에 데이터를 넣고 가공해서 리턴하는데 사용
리턴타입은 Optional<>이라서 이렇게 계속 메소드를 연달아 쓸 수 있음!
orElse()
: 데이터가 null일 때
map리턴은 원래 Optional박스에 담겨져있지만
.orElse()를 사용하면 리턴값이 Optional박스에 꺼내짐
Optional<String>이 String으로 리턴됨