我在Java 8中遇到了一个名为Functional Interface的新术语.
在使用lambda表达式时,我只能找到一个使用此接口的方法.
Java 8提供了一些内置的功能接口,如果我们想要定义任何功能接口,那么我们就可以使用@FunctionalInterface注释.它允许我们在接口中只声明一个方法.
例如:
@FunctionalInterface
interface MathOperation {
int operation(int a, int b);
}
Run Code Online (Sandbox Code Playgroud)
除了使用lambda表达式之外,它在Java 8中有多大用处?
这里的问题与我提出的问题不同.在使用Lambda表达式时,它询问为什么我们需要功能接口.我的问题是:为什么使用功能接口而不是直接使用lambda表达式?
阅读新Supplier界面我看不出它的用法有什么好处.我们可以看到它的一个例子.
class Vehicle{
public void drive(){
System.out.println("Driving vehicle ...");
}
}
class Car extends Vehicle{
@Override
public void drive(){
System.out.println("Driving car...");
}
}
public class SupplierDemo {
static void driveVehicle(Supplier<? extends Vehicle> supplier){
Vehicle vehicle = supplier.get();
vehicle.drive();
}
}
public static void main(String[] args) {
//Using Lambda expression
driveVehicle(()-> new Vehicle());
driveVehicle(()-> new Car());
}
Run Code Online (Sandbox Code Playgroud)
正如我们在该示例中所看到的,该driveVehicle方法需要一个Supplieras参数.为什么我们不把它改成期待Vehicle?
public class SupplierDemo {
static void driveVehicle(Vehicle vehicle){
vehicle.drive();
}
}
public static void main(String[] …Run Code Online (Sandbox Code Playgroud) 关于Java8 内置功能接口,我遇到过很多问题,包括this,this,this和this.但所有人都在问"为什么只有一种方法?" 或"如果我使用我的功能界面执行X,为什么会出现编译错误"等等.我的问题是:当我在自己的界面中使用lambda时,这些新功能接口的存在目的是什么?
请考虑以下来自oracle文档的示例代码:
// Approach 6: print using a predicate
public static void printPersonsWithPredicate(List<Person> roster,
Predicate<Person> tester) {
for (Person p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}
Run Code Online (Sandbox Code Playgroud)
好的,很好,但这可以用上面的自己的例子来实现(一个单一方法的接口并不新鲜):
// Approach 5:
public static void printPersons(<Person> roster,
CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}
interface CheckPerson {
boolean test(Person p);
}
Run Code Online (Sandbox Code Playgroud)
我可以将lambda传递给两个方法. …
可以说我有
public class Student {
public Integer getGrade() { return 1;}
}
Run Code Online (Sandbox Code Playgroud)
我想将此函数作为 java 中的函数传递到其他类(不是学生)
哪种语法允许我这样做?
Function<Student,Integer> = ***
Run Code Online (Sandbox Code Playgroud) 所以我试图通过这个测试:
public void testCountWithCondition() {
List<Integer> data = Arrays.asList(1, 3, 8, 4, 6);
int count = streamer.count(data, x -> x % 3 == 0);
assertEquals(2, count);
}
Run Code Online (Sandbox Code Playgroud)
我很难理解如何创建一个count可以将 lambda 表达式作为参数的方法。我看过其他帖子说您需要创建一个接口类,但是如何对其进行编程才能接受任何 lambda 表达式?另外,作业特别指出我需要使用流。谢谢!