public class FunctionPassingDrill {
/**Returns index of last match using matchFct, or -1 if no match*/public static <T> int findLast(List<T> elements, Function<T, Boolean> matchFct) {
for (int i = elements.size() - 1; i >= 0; i--) {
T nextElem = elements.get(i);
if (matchFct.apply(nextElem))
return i;
}
return -1;
}
}
//_test_
private void experiment() {
println("\ntest_findLast");
List<Integer> nums = Arrays.asList(10, 11, 12, 13, 14, 15);
int matchIndex;
//input integer, output boolean
Function<Integer, Boolean> isOddFct, isLargeFct;
println("Data: " + nums);
//fct returns true if input x is odd
isOddFct = (x) -> x % 2 == 1;
matchIndex = FunctionPassingDrill.findLast(nums, isOddFct);
println("Index of last odd number: " + matchIndex);
//fct returns true if input x is even
isLargeFct = (x) -> x % 2 == 0;
matchIndex = FunctionPassingDrill.findLast(nums, isLargeFct);
println("Last index of even number: " + matchIndex);
//fct returns true if input x is greater than 100
isLargeFct = (x) -> x > 100;
matchIndex = FunctionPassingDrill.findLast(nums, isLargeFct);
println("Index of last number greater than 100: " + matchIndex);
}