Lambda expressions, as an alternative to anonymous inner classes, provide a more concise way to define the implementation of functional interfaces: use the short syntax (parameters) -> expression to define anonymous functions. Suitable for situations where functional interfaces need to be implemented (only one abstract method). Can simplify tasks such as list sorting and thread definition.
Lambda Expressions
As an alternative to anonymous inner classes, Java 8 introduced lambda expressions. A lambda expression is a lightweight anonymous function that can be defined and used without declaring a class.
Syntax:
(parameters) -> expression
For example, the following code uses an anonymous inner class to add a listener for a button:
Button button = new Button(); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 实现事件处理代码 } });
Using a lambda expression it can be simplified to:
Button button = new Button(); button.addActionListener(e -> { // 实现事件处理代码 });
Functional interface
lambda expressions can only be used to implement functional interfaces, that is, interfaces that contain only one abstract method. Several built-in functional interfaces are provided in Java, such as Runnable
, Callable
and Comparator
.
Practical case
Use lambda expression to sort the list:
List<String> names = Arrays.asList("John", "Mary", "Bob"); // 使用匿名内部类 Collections.sort(names, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); // 使用 lambda 表达式 Collections.sort(names, (o1, o2) -> o1.compareToIgnoreCase(o2));
Use functional interface definition Thread:
// 使用匿名内部类 Thread thread = new Thread(new Runnable() { @Override public void run() { // 线程逻辑 } }); // 使用 lambda 表达式 Thread thread = new Thread(() -> { // 线程逻辑 });
Conclusion
Lambda expressions provide a cleaner and more elegant way to write code than anonymous inner classes. They simplify the use of functional interfaces and improve code readability and maintainability.
The above is the detailed content of What is the alternative to anonymous inner classes in Java?. For more information, please follow other related articles on the PHP Chinese website!