[Java] 함수형 프로그래밍과 람다식

람다

1. 함수형 프로그래밍과 람다식

  • 자바는 객체 지향 프로그래밍 : 기능을 수행하긴 위해서는 객체를 만들고 그 객체 내부에 멤버 변수를 선언하고 기능을 수행하는 메서드를 구현

  • 함수의 구현과 호출만으로 프로그래밍이 수행되는 방식

  • 함수형 프로그래밍(Functional Programming: FP)

  • 함수형 프로그래밍은 순수함수(pure function)를 구현하고 호출함으로써 외부 자료에 부수적인 영향(side effect)를 주지 않도록 구현하는 방식입니다. 순수 함수란 매개변수만을 사용하여 만드는 함수 입니다. 즉, 함수 내부에서 함수 외부에 있는 변수를 사용하지 않아 함수가 수행되더라도 외부에는 영향을 주지 않습니다.

  • 함수를 기반으로 하는 프로그래밍이고 입력받는 자료 이외에 외부 자료를 사용하지 않아 여려 자료가 동시에 수행되는 병렬처리가 가능합니다. 함수형 프로그래밍은 함수의 기능이 자료에 독립적임을 보장합니다. 이는 동일한 자료에 대해 동일한 결과를 보장하고, 다양한 자료에 대해 같은 기능을 수행할 수 있습니다.

2. 함수형 인터페이스 선언하기

@FunctionalInterface
public interface Add {

    public int add(int x, int y);
}
public interface MyMaxNumber {

    int getMax(int x, int y);
}
public class TestAdd {

    public static void main(String[] args) {

        Add addF = (x, y) -> x+y;
        System.out.println(addF.add(3, 5)); // 8

        MyMaxNumber max = (x, y) -> (x >= y) ? x: y;
        System.out.println(max.getMax(5, 10)); // 10
    }
}

3. 객체 지향 프로그래밍과 람다식 비교

@FunctionalInterface
public interface StringConcat {
    public void makeString(String s1, String s2);
}
public class StringConcatImpl implements StringConcat {
    @Override
    public void makeString(String s1, String s2) {
        System.out.println(s1 + " , " + s2);

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

        String s1 = "hello";
        String s2 = "world";

        //객체지향으로 구현현
        StringConcatImpl concat1 = new StringConcatImpl();
        concat1.makeString(s1, s2); // hello , world

        //람다식 구현 - 1
        StringConcat concat2 = (str1, str2) -> {
            System.out.println(str1 + " , " + str2);
        };

        concat2.makeString(s1, s2); // hello , world

        //람다식 구현 - 2
        StringConcat concat3 = new StringConcat() {
            @Override
            public void makeString(String s1, String s2) {
                System.out.println(s1 + " , " + s2);
            }
        };

        concat3.makeString(s1, s2); // hello , world
    }
}

댓글

Designed by JB FACTORY