자바 무료강의 2시간 완성을 시청하고 간략히 정리
한번만 사용되는 이름 없는 클래스
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.introduce();
Person person1 = new Person(){
// begin : 익명 클래스
@Override
public void introduce(){
System.out.println("사람사람2");
}
// end : 익명 클래스
};
person1.introduce();
}
}
class Person{
public void introduce(){
System.out.println("사람사람");
}
}
람다식: 간결한 형태의 코드 묶음
함수형 인터페이스: 람다식을 위한 인터페이스
@FunctionalInterface
자바의 람다 표현식은 함수형 인터페이스로만 사용 가능
(추상 메서드가 딱 하나면 함수형 인터페이스임)
이 어노테이션은 해당 인터페이스가 함수형 인터페이스 조건에 맞는지 검사해달라는 의미
@FunctionalInterface
interface 인터페이스명{// 함수형 인터페이스
// 하나의 추상 메소드
}
// 람다식
(전달 값1, 전달 값2, ... ) -> 코드; // 한 줄인 경우, 중괄호 제거 가능
(전달 값1, 전달 값2, ... ) -> {코드;코드;코드;}
public class Main {
public static void main(String[] args) {
MyFunction f1 = (x, y) -> x + y;// 람다식
System.out.println("f1의 결과: " + f1.calc(22, 100));
}
}
@FunctionalInterface
interface MyFunction { // 함수형 인터페이스
int calc(int x, int y); // 하나의 추상 메소드
}
배열, 컬렉션 데이터를 효과적으로 처리
public class Main {
public static void main(String[] args) {
List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7,8,9);
nums.stream()
.filter(n -> n % 2 == 0) // 짝수만 필터링
.map(n -> n * 2) // 각 요소 값을 2배로 변환
.forEach(System.out::println); // 결과 출력
}
}