Functional Interface in Java
Week 7
The Fold method in Java
1
2
3
4
5
public static <A, B> A fold(BiFunction<A,B,A> folder, A s, List<B> bList){
if (bList.isEmpty()) return s;
B b = bList.get(0);
return folder.apply(fold(folder, s, bList.subList(1, bList.size())), b);
}
Examples of how to use fold
1
2
3
4
5
6
7
8
9
10
11
12
13
Integer sum = fold((Integer::sum), 0, List.of(10, 10,20));
public static Integer length(int state, int a) {
return state + 1;
}
Integer length = fold((Application::length), 0, List.of(10, 10,20));
public static List<Integer> incrementByOne(List<Integer> state, int a) {
//If we don't add (0) as starting index it will be reversed list
state.add(0, a + 1);
return state;
}
List<Integer> incrementByOne = fold((Application::incrementByOne), new ArrayList<>(), List.of(10, 10,20));
Beware the functions length
and incrementByOne
returns Integer
and List<Integer>
which is the state it returns. So we notice in the method length
it does not even use the parameter a, it just increments 1 to state and returns the new state.
Most of these have a running time on \(O(n)\) time since they require to go throuch each element of the list and do something.