As we all know, Java 8 supports lambda expressions, and some common operations can be implemented through lambda, such as traversing List, or implementing an event interface, as well as Swing events that we are familiar with, as shown in the following cases:
// Before Java 8: JButton b1= new JButton("BeforeJava8"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("Button push"); } }); // Java 8: JButton b2= new JButton("Java8"); b2.addActionListener((e) -> { System.out.println("Button push"); });
Sometimes we are confused: Java is clearly OOP language, Lambda expression does not destroy the encapsulation characteristics of OOP? However, Lambda is actually implemented with an interface, which has only one method. Let's look at the following cases:
/** * @author wangwenhai */ interface PrintHandler { void print(int[] array); } public class Main { static void print(int[] array, PrintHandler printHandler) { printHandler.print(array); } public static void main(String[] args) { int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; print(array, new PrintHandler() { @Override public void print(int[] array) { for (int i = 0; i < array.length; i++) { System.out.println("array:" + i); } } }); } }
This is a simple way to traverse an array by passing in an interface, and then the user realizes the specific traversal method. It looks like a very common anonymous interface implementation, but if we use Java 8, this code will become more streamlined:
/** * @author wangwenhai */ interface PrintHandler { void print(int[] array); } public class Main { private static void print(int[] array, PrintHandler printHandler) { printHandler.print(array); } public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9}; print(array, array1 -> { for (int i = 0; i < array1.length; i++) { System.out.println("array:" + i); } }); } }
As you may have noticed, the implementation of the anonymous interface here is missing, as if a piece of code has never been seen before. In fact, this is the implementation of lambda in Java 8:
print(array, array1 -> { for (int i = 0; i < array1.length; i++) { System.out.println("array:" + i); } });
Aray1 is a parameter passed to the interface, which directly omits the implementation process of the interface, because only one method, so this parameter is passed directly into the print method.
We use a graph to represent the process from OOP to FP (Functional Programming).