java8 interface,Java8中的函数式接口

f53bed5e3dc6f27286dac93ecc63df4a.png函数式接口是只包含一个抽象方法的接口。它们只能展示一种功能。从Java8开始,可以使用lambda表达式来表示函数式接口的实例。函数式接口可以有任意数量的默认方法。Runnable、ActionListener和Comparable是函数接口的一些示例。

在Java8之前,我们必须创建匿名的内部类对象或实现这些接口。

// Java program to demonstrate functional interface

class Test

{

public static void main(String args[])

{

// create anonymous inner class object

new Thread(new Runnable()

{

@Override

public void run()

{

System.out.println("New thread created");

}

}).start();

}

}

输出:

New thread created

从Java 8开始,我们可以将lambda表达式分配给它的函数接口对象,如下所示:

// Java program to demonstrate Implementation of

// functional interface using lambda expressions

class Test

{

public static void main(String args[])

{

// lambda expression to create the object

new Thread(()->

{System.out.println("New thread created");}).start();

}

}

输出:

New thread created

@FunctionalInterface

@FunctionInterface注解用于确保函数接口不能有多个抽象方法。如果存在多个抽象方法,编译器会标记一条“Unexpected@functioninterface annotation”消息。但是,不强制使用此注释。

// Java program to demonstrate lamda expressions to implement

// a user defined functional interface.

@FunctionalInterface

interface Square

{

int calculate(int x);

}

class Test

{

public static void main(String args[])

{

int a = 5;

// lambda expression to define the calculate method

Square s = (int x)->x*x;

// parameter passed and return type must be

// same as defined in the prototype

int ans = s.calculate(a);

System.out.println(ans);

}

}

输出:

25

java.util.function

这个java.util.function包是Java8中的包,它包含许多内置函数接口,如:

Predicate:Predicate接口有一个抽象方法测试,它为指定的参数提供一个布尔值作为结果。它的原型是

public interface Predicate

{

public boolean test(T t);

}

BinaryOperator:BinaryOperator接口有一个抽象方法apply,它接受两个参数并返回相同类型的结果。它的原型是

public interface BinaryOperator

{

public T apply(T x, T y);

}

Function:Function接口有一个抽象方法apply,它接受T类型的参数并返回R类型的结果

public interface Function

{

public R apply(T t);

}

代码示例:

// A simple program to demonstrate the use

// of predicate interface

import java.util.*;

import java.util.function.Predicate;

class Test

{

public static void main(String args[])

{

// create a list of strings

List names =

Arrays.asList("Geek","GeeksQuiz","g1","QA","Geek2");

// declare the predicate type as string and use

// lambda expression to create object

Predicate p = (s)->s.startsWith("G");

// Iterate through the list

for (String st:names)

{

// call the test method

if (p.test(st))

System.out.println(st);

}

}

}

输出:

Geek

GeeksQuiz

Geek2

要点:

1. 函数式接口只有一个抽象方法,但可以有多个默认方法。

2. @FunctionInterface注解用于确保一个接口不能有多个抽象方法。此注解的使用是可选的。

3. 这个java.util.function函数包中包含许多Java8中的内置函数接口。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值