클래스의 멤버 사용

람다식 실행 블록에는 클래스의 멤버인 필드와 메소드를 제약없이 사용할 수 있다.

람다식 실행 블록내에서 this는 람다식을 실행한 객체의 참조이다.


Exam    ( UsingThis 의 Filed2 와 Inner의 Filed2이름이 같을때 this 

public class UsingThis {
public int outterField1 = 10;
public int Filed2 = 1000;

class Inner {
int innerField1 = 20;
int Field2 = 2000;

void method() {
MyFunctionalInterface fi = () -> {
System.out.println("outterField = " + outterField1); //결과값 10
System.out.println("innerField = " + innerField1); //결과값 20

System.out.println("Field2 = " + Field2); // 결과값 2000
System.out.println("Field2 = " + Field2); // 결과값 2000

System.out.println("UsingThis.this.Filed2 = " + UsingThis.this.Filed2); //결과값 1000
System.out.println("this.Field2 = " + this.Field2); // 또는 Field2 호출 결과값 2000
};
fi.method();
}
}
}



로컬 변수의 사용

람다식은 함수적 인터페이스의  익명 구현 객체를 생성한다.

람다식에서 사용하는 외부 로컬 변수는 final 특성을 갖는다.

Exam


public class UsingLocalVariable {
void method(int arg) {
int localVar = 40;

// arg = 31; 수정하려고하면 에러 발생 아래 람다식에서 사용했기때문에 final
// localVar = 20; 수정하려고하면 에러 발생 아래 람다식에서 사용했기때문에 final

MyFunctionalInterface fi = () -> {
System.out.println("arg = " + arg); //arg 는 final특성을 가짐
System.out.println("localVar = " + localVar); //localVar 는 final특성을 가짐
};
fi.method();
}
}



'JAVA > JAVA' 카테고리의 다른 글

자바 컬렉션) Set 컬렉션  (0) 2018.06.14
람다식) 표준 API의 함수적 인터페이스  (0) 2018.06.10
람다식 타겟 타입과 함수적 인터페이스  (0) 2018.06.09
람다식 기본 문법  (0) 2018.06.09
람다식이란?  (0) 2018.06.09

타겟 타입(target type)

람다식이 대입되는 인터페이스를 말한다.                                    인터페이스(타겟 타입) 변수 = 람다식;

익명 구현 객체를 만들 때 사용할 인터페이스이다.


함수적 인터페이스(functional interface)

모든 인터페이스는 람다식의 타겟 타입이 될 수 없다.

람다식은 하나의 메소드를 정의하기 떄문에..

나의 추상 메소드만 선언된 인터페이스만 타겟 타입이 될 수 있다.


함수적 인터페이스

하나의 추상 메소드만 선언된 인터페이스를 말한다.


@FunctionalInterface  어노테이션

하나의 추상 메소드만을 가지는지 컴파일러가 체크하도록 함

두 개 이상의 추상 메소드가 선언되어 있으면 컴파일 오류 발생


매개 변수와 리턴값이 없는 람다식

@FunctionalInterface

public interface MyFunctionalInteface (

              public void method();

}

            MyFunctionalInterface fi = () -> { ... }

            fi.method(); 



Exam

                      //하나의 추상 메소드만을 가지는지 컴파일러가 체크하도록 함
@FunctionalInterface // 두 개 이상의 추상 메소드가 선언되어 있으면 컴파일 오류 발생
public interface MyFunctionalInterface {
public void method();
// public void method2(); 주석을 해제하면 컴파일 오류 발생
}



public class MyFunctionalInterfaceExample {
public static void main(String[] args) {

MyFunctionalInterface fi;

fi = () -> {
String str = "method call1";
System.out.println(str);
};
fi.method(); //실행결과 method call1

fi = () -> { System.out.println("method call2");};
fi.method(); //실행결과 method call2

fi = () -> System.out.println("method call3"); //실행문이 하나 이므로 중괄호 생략
fi.method(); //실행결과 method call3

fi = new MyFunctionalInterface() {
@Override
public void method() {
System.out.println("method call4");
}
};
fi.method(); //실행결과 method call4
}
}


매개변수가 있는 람다식

@FunctionalInterFace

public interface MyFunctionalInterface {

       public void method(int x);

      MyFunctionalInterface fi = (x) -> { ... }  또는  x -> { ... }

      fi.method(5) 


Exam

                      //하나의 추상 메소드만을 가지는지 컴파일러가 체크하도록 함
@FunctionalInterface // 두 개 이상의 추상 메소드가 선언되어 있으면 컴파일 오류 발생
public interface MyFunctionalInterface {
public void method(int x); //매개변
// public void method2(); 주석을 해제하면 컴파일 오류 발생
}


public class MyFunctionalInterfaceExample {
public static void main(String[] args) {

MyFunctionalInterface fi;

fi = (x) -> {
int result = x * 5;
System.out.println(result);
};
fi.method(2); //실행 결과 10


fi = (x) -> System.out.println(x * 5); //실행문이 하나일 경우 중괄호 생략 {}
fi.method(2); //실행 결과 10

fi = x -> System.out.println(x * 5); //매개변후가 하나일 경우 괄호() 생략
fi.method(2); //실행 결과 10
}
}


리턴값이 있는 람다식

@FunctionalInterFace

public interface MyFunctionalInterface {

       public int void method(int x, int y);

 MyFunctionalInterFace fi = (x, y) -> { ...; return 값; }

 int result = fi.method(2, 5)




 MyFunctionalInterface fi = (x, y) ->{

      return x + y;

 MyFunctionalInterFace fi = (x, y) -> x + y;

  MyFunctionalInterFace fi = (x, y) -> {

     return sum(x, y);

}

 MyFunctionalInterFace fi = (x, y) -> sum(x, y); 


Exam

                      //하나의 추상 메소드만을 가지는지 컴파일러가 체크하도록 함
@FunctionalInterface // 두 개 이상의 추상 메소드가 선언되어 있으면 컴파일 오류 발생
public interface MyFunctionalInterface {
public int method(int x, int y); //매개변수가 2개 int타입 리턴
// public void method2(); 주석을 해제하면 컴파일 오류 발생
}


public class MyFunctionalInterfaceExample {
public static void main(String[] args) {

MyFunctionalInterface fi;

fi = (x, y) -> {
int result = x + y;
return result;
};
System.out.println(fi.method(2,5)); //실행 결과 7

fi = (x, y) -> { return x + y; };
System.out.println(fi.method(2,5)); //실행 결과 7

fi = (x, y) -> x + y; //중괄호 블럭에 return문만 있을경우 중괄호 생략가능, return 생략가능
System.out.println(fi.method(2,5)); //실행 결과 7


//아래의 static int sum() 으로 실행
fi = (x, y) -> sum(x, y); // == {return sum(x, y);};
System.out.println(fi.method(2,5)); //실행 결과 7

}
public static int sum(int x, int y) {
return (x + y);
}
}


함수적 프로그램

y = f(x) 형태의 함수로 구성된 프로그래밍 기법

데이터를 매개값으로 전달하고 결과를 받는 코드들로 구성

객체 지향 프로그래밍 보다는 효율적인 경우

         대용량 데이터의 처리시에 유리
데이터 포장 객체를 생성후 처리하는 것 보다, 데이터를 바로 처리하는 것이 속도에 유리
멀티코어 cpu에서 데이터를 병렬 처리하고 취합할 때 객체보다는 함수가 유리

이벤트 지향 프로그래밍(이벤트가 발생하면 핸들러 함수 실행)에 적합
반복적인 이벤트 처리는 핸들러 객체보다는 핸들러 함수가 적합


현대적 프로그래밍 기법

객체지향 프로그래밍  + 함수적 프로그래밍


자바 8부터 함수적 프로그래밍 지원

람다식 (Lamda Expresstions)을 언어 차원에서 지공

람다 계산법에서 사용된 식을  프로그래밍 언어에 접목

익명 함수(anonymous function)을 생성하기 위한 식

(타입 매개변수, ...)  -> { 실행문; ...}


자바에서 람다식을 수용한 이유

코드가 매우 간결해진다

컬렉션 요소(대용량 데이터)를 필터링 또는 매핑해서 쉽게 집계할 수 있다.



자바는 람다식을 함수적 인터페이스(한개의 메서드를 가지고 있는 메서드)의 익명 구현 객체로 취급

어떤 인터페이스를 구현할지는 대입되는 인터페이스에 달려이있다.

 Runnable runnable = () -> { ... }         ---------람다식
f

Runnable runnable = new Runnable(){
public void run() {...}
};


+ Recent posts