I am trying to learn the features of Java 8 especially the functional programming aspect of it. So I am trying to solve a problem: Find Leaders in an Array - A leader is an element which is larger than all the elements in the array to its right.
For example:
Input Array: { 98, 23, 54, 12, 20, 7, 27 }
Output: Leaders - 27 54 98
Now, I have solved this using the usual iterative approach as shown below.
private static void findLeaders(int[] array) {
int currentLeader = array[array.length - 1];
System.out.println(currentLeader);
for(int i = array.length - 1; i >= 0; i--) {
if(array[i] > currentLeader) {
System.out.println(array[i]);
currentLeader = array[i];
}
}
}
I tried solving it using Java 8, but I couldn't do much apart from writing this piece of code, which again had compilation error:
Function<Integer, Integer> checkLeader = i -> i > currentLeader ? i : currentLeader;
Error: Local variable currentLeader defined in an enclosing scope must be final or effectively final
Now how do I solve the same problem using the features of Java 8.