// 익명 클래스로 Runnalbe을 구현
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Start to new thread!");
}
});
thread.start();
// 람다 표현식으로 단순하게 표현
Thread thread = new Thread(() -> System.out.println("Start to new thread!"));
thread.start();
()
, 화살표->
, 바디함수
로 구성(str) -> System.out.println(str);
str -> System.out.println(str);
(i) -> i + 10;
(i) -> {
int result = i + 10;
return result;
};
파라미터 x, 리턴 타입 o
() -> Integer.MAX_VALUE;
run()
하나만 존재하므로 함수형 인터페이스라 할 수 있음@FunctionalInterface
어노테이션 제공(Java 8 이후)@FunctionalInterface
public Interface Cat {
String name(String name);
}
@FunctionalInterface
를 이용해 명시한 함수형 인터페이스Cat cat = new Cat() {
@Override
public String name(String name) {
return "고양이의 이름은 " + name + "입니다.";
}
};
Cat cat = (name) -> "고양이의 이름은 " + name + "입니다.";
System.out.println(cat.name("뚱냥이"));
Function<T, R>
의 형태가 기본이며, T는 매개변수 타입, R은 리턴 타입을 지칭compose
, andThen
, identity
가 구현되어 있음boolean
값 리턴UnaryOperator
, BinaryOperator
를 이용해 매개변수 개수 구분public interface Sample {
String returnHello(String msg);
default void hello(String msg) {
System.out.println("hello " + msg);
}
}
니체가 작성한 책의 ISBN 정보 필요하며, 정렬은 책이름 기준으로 정렬
books.sort(Comparator.comapring(Book::getName));
List<String> booksWrittenByNietzsche = new ArrayList<>();
for (Book book: books) {
if (book.getAuthor().equals("Friedrich Nietzsche")) {
booksWrittenByNietzsche.add(book.getIsbn());
}
}
List<String> booksWrittenByNietzsche =
books.stream()
.fillter(book -> book.getAuthor().equals("Friedrich Nietzsche"))
.sorted(Comparator.comparing(Book::getName))
.map(Book::getIsbn)
.collect(Collectors.toList());
Stream<T>
형태로 스트림 반환되면 중간연산, 그렇지 않으면 종료 연산filter()
, sorted()
는 모두 중간연산public class BookService {
public String getAuthorName(Book book) {
if(book == null) {
throw new NullPointerException("this book is null");
}
Author author = book.getAuthor();
if (author == null) {
throw new NullPointerException("This author is null");
}
String authorName = bookService.getAuthorName(book);
if (authorName == null) {
throw new NullPointerException("This author name is null");
}
}
}
public class BookService {
public Optional<String> getAuthorName(Book book) {
return Optional.ofNullable(book)
.map(bookObject -> bookObject.getAuthor())
.map(authorObject -> authorObject.getName());
}
}
Optional<String>
을 명시함으로써 빈 결과값이 반환될 수 있음을 인지Date
, Calendar
외에 날짜 API가 추가Instant
, LocalDate
, LocalTime
, LocalDateTime
이 추가 됨Duration
, Period
와 같은 날짜와 시간 간격 클래스, DateTimeFormatter
와 같은 날짜 포맷 표현하기 위한 클래스도 추가-XX:PermSize
, -XX:MaxPermSize
삭제 후 XX:MetaspaceSize
, -XX:MaxMetaspzceSize
옵션이 추가참조
Java8 변경점: https://bbubbush.tistory.com/23
Functional Interface 기본함수: https://futurecreator.github.io/2018/08/02/java-jdk-functional-interfaces-api/