익명 클래스(Anonymous Class)
한 번만 사용되는 이름 없는 클래스
class Person {
public void introduce() {
System.out.println("Hi");
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person(); { // 객체 생성후 중괄호 내부에
@Override // 어노테이션
public void introduce() { // 익명함수
System.out.println("Hello");
}
};
person.introduce();
}
}
람다식(Lambda)
간결한 형태의 코드 묶음
메소드의 동작을 간단하게 표현하기 위해서 사용 됨
/*
(전달값1, 전달값2, ...) -> {코드}
*/
public int add(int x, int y) {
return x + y;
}
// 접근 제어자, 반환형, 이름 제거
// 파라미터와 필드사이에 -> 삽입
// 자료형 제거
// 중괄호, return 제거
// 중괄호 제거는 메소드가 하나의 문장으로 이루어진 경우만 가능
(x, y) -> x + y // (매개변수) -> 실행코드
// 간소화된 모습
함수형 인터페이스(Functional Interface)
람다식을 위한 인터페이스
딱 하나의 추상메소드를 가져야 한다는 제약이 있음
/*
@FunctionalInterface
interface 인터페이스명 {
// 하나의 추상메소드
}
*/
@FunctionalInterface
interface Calculator {
int calculate(int x, int y); // 하나의 추상메소드
}
public class Main {
public static void main(String[] args) {
Calculator add = (x,y) -> x + y; // 람다식
int result = add.calculate(2,3);
System.out.println("2+ 3 = " + result);
}
}
스트림(Stream)
배열, 컬렉션 데이터를 효과적으로 처리 (필터링)
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,4,5);
numbers.stream()
.filter(n -> n % 2 == 0) // 짝수만 필터링
.map(n -> n * 2) // 각 요소 값을 2배로 변환
.forEach(System.out::println); // 4 한줄 8 한줄 출력
}
}
'Java > Java Language' 카테고리의 다른 글
[Java 기초] 쓰레드 Thread, Runnable, Join, MultiThread, Synchronized (1) | 2024.11.29 |
---|---|
[Java 기초] 예외처리 Exception, Try-Catch, Throw, Finally (0) | 2024.11.28 |
[Java 기초] 리스트 list (0) | 2024.11.28 |
[Java 기초] 클래스 class (0) | 2024.11.28 |
[Java 기초] 아스키코드 ascii code, 메소드 method (0) | 2024.11.26 |