JAVA
람다식
연93
2022. 10. 12. 22:16
y = f(x) 형태의 함수로 구성된 프로그래밍 기법
데이터를 매개값으로 전달하고 결과를 받는 코드들로 구성
객체지향 프로그래밍 보다는 효율적인 경우
- 대용량 데이터의 처리시에 유리
- 데이터 포장 객체를 생성후 처리하는 것 보다, 데이터를 바로 처리하는 것이 속도에 유리
- 멀티코어 cpu에서 데이터를 병렬 처리하고 취합할 때 객체보다는 함수가 유리
- 코드가 매우 간결해진다.
- 컬렉션요소(대용량 데이터)를 필터링 또는 매핑해서 쉽게 집계할 수 있다.
/*
함수적 인터페이스 : 추상메소드 1개만을 구성요소로 하는 인터페이스. 목적? 람다식문법을 사용
*/
@FunctionalInterface // @명령어 : 어노테이션. 인터페이스에서 추상메소드를 반드시 1개만 사용가능.
// 추상메소드를 더 추가시 문법적으로 에러발생.
public interface MyFunctionalInterface {
//매개변수 없고, 리턴타입 없는 형태. -> 람다식구문표현
public void method();
}
public class MyFunctionalInterfaceExample {
public static void main(String[] args) {
//익명구현객체
/*
MyFunctionalInterface myFunctionalInterface = new MyFunctionalInterface() {
@Override
public void method() {
String str = "method call1";
System.out.println(str);
}
};
*/
//람다식문법 : 익명구현객체의 내용을 람다식구문.
//익명함수. 일반적인 함수형태 : 리턴타입 메소드명(매개변수,....) {............}
MyFunctionalInterface fi;
// public void method(); 추상메소드를 구현한 의미.
fi = () -> {
String str = "method call1";
System.out.println(str);
};
fi.method();
// 중괄호 {} 안에 명령문이 하나인 경우에는 {} 생략가능
fi = () -> { System.out.println("method call2"); };
fi.method();
fi = () -> System.out.println("method call3");
fi.method();
//클래스를 구현한 형태.
MyFunctionalInterface fi2 = new MyFunctionInterfaceImpl();
fi2.method();
}
}
public class MyFunctionInterfaceImpl implements MyFunctionalInterface {
@Override
public void method() {
System.out.println("클래스를 구현한 형태");
}
}