Dev/Java

Higher-Order Function : 고계함수(고차함수)

마이스토리 2016. 4. 6. 15:32

다음 중 한 가지 이상을 만족하는 함수

- 파라미터로 함수를 받을 수 있다.

- 결과값으로 함수를 리턴한다.


예제)

public class HigherOrderFunctionExamples {


public static void main(String[] args) {

Function<Function<Integer, String>, String> f1 = g -> g.apply(10);

System.out.println(

f1.apply(i -> "#" + i) // "#10"

); 

Function<Integer, Function<Integer, Integer>> f2 = i -> (i2 -> i + i2);

System.out.println(

f2.apply(1).apply(9) // 10

);

List<Integer> list = Arrays.asList(1,2,3,4,5);

List<String> mappedList = map(list, i -> "#"+i);

System.out.println(mappedList); //[#1, #2, #3, #4, #5]

System.out.println(

list.stream()

.map(i -> "#"+i)

.collect(toList())

);

Function<Integer, Function<Integer, Function<Integer, Integer>>> f3 = i1 -> i2 -> i3 -> i1 + i2 + i3;

System.out.println(f3.apply(1).apply(2).apply(3)); //6

}

private static <T, R> List<R> map(List<T> list, Function<T, R> mapper){

List<R> result = new ArrayList<R>();

for(T t : list){

result.add(mapper.apply(t));

}

return result;

}


}