简体   繁体   English

使用 lambda 表达式创建匿名类?

[英]Create an anonymous class using lambda expression?

Java 8 支持 lambda 表达式,我想知道我们是否可以用 lambda 表达式替换匿名类?

According to the Oracle docs on Lambda expressions, they are the same as anonymous classes implementing functional interfaces (interfaces having only one method).根据有关 Lambda 表达式的Oracle 文档,它们与实现功能接口(只有一种方法的接口)的匿名类相同。

So if you have a method which takes an argument which has a functional interface as its reference type, you can use a lambda expression while calling that method.因此,如果您有一个方法接受一个参数,该参数具有一个函数式接口作为其引用类型,您可以在调用该方法时使用 lambda 表达式。 Example:-例子:-

public boolean testString(Predicate<String> tester, String str);

When calling testString , you can make use of a lambda expression to reduce the amount of code needed to write a comparator:-调用testString ,您可以使用 lambda 表达式来减少编写比较器所需的代码量:-

boolean result = testString(s -> { /* implement Predicate.test */}, str);

Why are lambda expressions useful?为什么 lambda 表达式有用?

When you want to leave the core functionality of a method to the caller without writing explicit classes/anonymous classes.当您想将方法的核心功能留给调用者而不编写显式类/匿名类时。 Expanding the example taken above:-扩展上面的例子:-

boolean isStringPalindrome = testString(s -> { /* code to check if string is palindrome */}, "madam");
boolean doesStringContainVowels = testString(s -> { /* code to check if string contains vowels */}, "abc");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM