Java 8은 2014년 출시된 Java의 가장 큰 업데이트 중 하나로 함수형 프로그래밍을 지원하는 람다 표현식, 스트림 API, 인터페이스의 기본 메서드 등을 도입하여 개발자의 생산성을 크게 향상시켰습니다.
주요 특징
// Runnable 인터페이스 사용
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Hello, Java 7!");
}
};
new Thread(runnable).start();
Runnable runnable = () -> System.out.println("Hello, Java 8!");
new Thread(runnable).start();
@FunctionalInterface 어노테이션으로 명시 가능 Predicate, Function, Consumer, Supplier 등의 기본 제공 인터페이스 사용 가능 @FunctionalInterface
interface MyFunction {
int add(int a, int b);
}
public class LambdaExample {
public static void main(String[] args) {
MyFunction sum = (a, b) -> a + b;
System.out.println(sum.add(10, 20)); // 30
}
}
import java.util.Arrays;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Java", "Python", "Kotlin", "Go");
names.stream()
.filter(name -> name.length() > 4)
.forEach(System.out::println);
}
}
// 출력: Python, Kotlin
interface Vehicle {
default void start() {
System.out.println("Vehicle is starting...");
}
}
class Car implements Vehicle {
public void drive() {
System.out.println("Car is driving...");
}
}
public class DefaultMethodExample {
public static void main(String[] args) {
Car car = new Car();
car.start(); // 인터페이스 기본 메서드 호출
car.drive();
}
}
LocalDate, LocalTime, LocalDateTime, ZonedDateTime 등 제공 java.util.Date와 SimpleDateFormat의 단점을 해결 import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeExample {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("오늘 날짜: " + today);
LocalDateTime now = LocalDateTime.now();
System.out.println("현재 시간: " + now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
}
}
null을 직접 다루지 않고 안전하게 값을 처리 orElse(), orElseGet(), ifPresent() 등의 메서드 제공 import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
Optional<String> optional = Optional.ofNullable(null);
System.out.println(optional.orElse("기본값")); // 기본값
}
}
parallel() 활용) Optional 활용) | 버전 | 주요 변경 사항 |
|---|---|
| Java 9 | 모듈 시스템 (Project Jigsaw), Stream.ofNullable() |
| Java 10 | var 키워드 도입 (지역 변수 타입 추론) |
| Java 11 | HttpClient 추가, String 관련 메서드 강화 |
| Java 17 | 패턴 매칭, sealed class 도입 |
Java 8은 기존 Java보다 더 간결하고 함수형 스타일의 코딩이 가능하도록 개선되었습니다.
람다 표현식과 스트림 API 덕분에 코드 가독성이 높아졌고 Optional을 활용해 Null 처리를 더 안전하게 할 수 있었습니다.
실무에서도 Java 8 이상의 기능을 적극 활용하면 유지보수성과 성능을 모두 향상시킬 수 있다는 점이 인상적이었습니다.