java8 API 函数式接口
简介
14年,Oracle公司如期发布了Java 8正式版,Java8提供了强大的流式处理及函数式接口编程
函数式接口编程,相信很多人在javascript中都使用过,比如回调函数,如今Java8也吸收了诸多的其它语言优点。
线程创建(8以前的写法)
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.printf(Thread.currentThread().getName());
}
});
thread.start();
Java8的函数式接口写法
//1Java8 lambda表达式写法
Thread thread = new Thread(() -> {
System.out.printf(Thread.currentThread().getName());
});
//对于{}里面只有一条语句的写法
Thread thread1 = new Thread(() -> System.out.println(Thread.currentThread().getName()));
//这种写法,不知道各位看官看着是什么感想
Student student = new Student("yang", 2);
new Thread(student::getName);
对比一下
List<Student> list = new ArrayList<>();
list.add(new Student("yang", 20));
list.add(new Student("hehe", 25));
list.add(new Student("jiana", 18));
//对集合进行排序,以前的写法
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge(); }
});
//Java8 lambda表达式的写法
Collections.sort(list, (o1, o2) -> o1.getAge()-o2.getAge());
Java8函数式编程可以使用lambda表达式,让代码更加简洁高效,当然对于许多如果刚接触的小伙伴来说,如果没有经过学习lambda式的写法,看起来也会云里雾里的,毕竟写法是高效了,但可读性确实要差一些了,对于改bug的同鞋来讲,难度是否又增加许多?
JDK 1.8 API包含了很多内建的函数式接口,在老Java中常用到的比如Comparator或者Runnable接口,这些接口都增加了@FunctionalInterface注解以便能用在lambda上。
标注为FunctionalInterface的接口被称为函数式接口,该接口只能有一个自定义方法,但是可以包括从object类继承而来的方法。如果一个接口只有一个方法,则编译器会认为这就是一个函数式接口。是否是一个函数式接口,需要注意的有以下几点:
1.该注解只能标记在”有且仅有一个抽象方法”的接口上。
2.JDK8接口中的静态方法和默认方法,都不算是抽象方法。
3.接口默认继承java.lang.Object,所以如果接口显示声明覆盖了Object中方法,那么也不算抽象方法。
4.该注解不是必须的,如果一个接口符合”函数式接口”定义,那么加不加该注解都没有影响。加上该注解能够更好地让编译器进行检查。如果编写的不是函数式接口,但是加上了@FunctionInterface,那么编译器会报错。
5.在一个接口中定义两个自定义的方法,就会产生Invalid ‘@FunctionalInterface’ annotation; FunctionalInterfaceTest is not a functional interface错误.
现如今,我们则从Function常用函数入口,真正了解一下。
1.Function:接受一个对象,返回一个对象
/**
* @param <T> the type of the input to the function
* @param <R> the type of the result of the function
* @since 1.8
*/
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
Function 内部有一个有一个apply(待子类实现)的方法,调用apply,回传R结果,通过泛型保证apply函数的入参入及返回值的类型。
基本使用:
对数据进行处理将String类型转换成double类型,代码如下:
//先定义好这个函数功能
Function<String, Double> stringToDouble = ((string) -> Double.parseDouble(string));
//再使用函数功能
System.out.println(stringToDouble.apply("20.25"));
异步回调处理
//将student的名字,通过回调的方式放入name变量中,name变量必须是Atomica类型的,因为交给别人,别人可以用线程来做
public class MainTest {
public static void main(String[] args) {
Student student2 = new Student("yanchuanbin", 25);
AtomicReference<String> name = new AtomicReference<>("");
String otherParams = "";
new Operator(student2).handler(otherParams, (student) -> {
System.out.println("here1 = " + Thread.currentThread().getName());
name.set(student.getName());
return null;
});
}
}
class Operator {
Student student;
public Operator(Student student) {
this.student = student;
}
public void handler(String otherParams, Function<Student, Void> callback) {
System.out.println("here2 = " + Thread.currentThread().getName());
ThreadFactory threadFactory;
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> callback.apply(student));
}
}
输出
here2 = main
here1 = pool-1-thread-1
2.Supplier:生产者,无参数,只有返回值
Supplier生产者,提前定义好生产方法,通过get()获取返回值,源码如下
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
作为生产者,基本使用
// Supplier<Student> supplier2 = new Supplier() {
// @Override
// public Student get() {
// return new Student("aa",new Random().nextInt(20);
// }
// };
Supplier<Student> supplier = () -> new Student("yanchuanbin", 2);
Student student = supplier.get();
3.Consumer:消费者,有入参,但无返回值
Consumer消费者,传入一个参数,消费后无返回值,源码如下
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
基本使用
Student student = new Student("yanchuanbin", 25);
//旧写法
// Consumer<Student> consumer = new Consumer<Student>() {
// @Override
// public void accept(Student student) {
// System.out.println(student.getAge());
// }
// };
//lambad写法
Consumer<Student> consumer = (student1 -> System.out.println(student1.getAge()));
consumer.accept(student);
4.Predicate:断言,有参数T,返回固定类型boolean
断言式接口其参数是<T,boolean>,源码如下
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
基本使用
Predicate<Student> studentEqualsPredicate = (student) -> student.getAge() > 10;
Student student = new Student("yanchuanbin", 25);
System.out.println(studentEqualsPredicate.test(student));
输出
true
5.UnaryOperator:接收T对象,返回T对象
对对象进行处理,处理后,将原来的对象返回,入参和返回值都是T,源码如下:
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
/**
* Returns a unary operator that always returns its input argument.
* @param <T> the type of the input and output of the operator
* @return a unary operator that always returns its input argument
*/
static <T> UnaryOperator<T> identity() {
return t -> t;
}
}
基本使用
UnaryOperator<Student> identity = (x -> {
return new Student(x.getName(), x.getAge()+1);
});
//生产一个大一岁的哥出来,名字是一样的
Student student1 = identity.apply(student);
6.BinaryOperator:传入两个T对象,返回T对象
继承自BiFunction,传入两个T类型的对象,返回一个T类型的对象,源码如下
* @param <T> the type of the operands and result of the operator
*
* @see BiFunction
* @see UnaryOperator
* @since 1.8
*/
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
BiFunction源码如下
@FunctionalInterface
public interface BiFunction<T, U, R> {
/**
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);
基本使用
//传入两个学生,返回两个学生中年龄较大的学生对象
BinaryOperator<Student> getMaxAgeStudentHandler =
(student1, student2) -> student1.getAge() > student2.getAge() ? student1 : student2;
Student student1 = new Student("ya",20);
Student student2 = new Student("wa",25);
Student maxAgeStudent = getMaxAgeStudentHandler.apply(student1,student2);
java8 API 函数式接口的更多相关文章
- [译]Java8的函数式接口
Java8引入了 java.util.function 包,他包含了函数式接口,具体的描述在以下api说明文档中: 函数式接口为lambda表达式和方法引用提供目标类型.每个函数式接口有一个单独的抽象 ...
- java8的函数式接口
函数式接口 就是在java8里允许你为一个接口(只有一个实现的,声明为FunctionalInterface注解的)实现一个匿名的对象,大叔感觉它与.net平台的委托很类似,一个方法里允许你接收一个方 ...
- JAVA8之函数式接口
由于JDK8已经发布一段时间了,也开始逐渐稳定,未来使用JAVA语言开发的系统会逐渐升级到JDK8,因为为了以后工作需要,我们有必要了解JAVA8的一些新的特性.JAVA8相对JAVA7最重要的一个突 ...
- Java8 Functional(函数式接口)
Functional 函数式(Functional)接口 只包含一个抽象方法的接口,称为函数式接口. 你可以通过 Lambda 表达式来创建该接口的对象.(若 Lambda 表达式抛出一个受检异常(即 ...
- java8 常用函数式接口
public static void main(String[] args) { // TODO Auto-generated method stub //函数式接口 Function<Inte ...
- Java8常见函数式接口总结
函数式接口 函数式接口:有且仅有一个抽象方法的接口. 使用@FunctionalInterface注解来标记.如果接口不是函数式接口就会编译出错 满足条件的接口即使不加上注解,那也是函数式接口 函数式 ...
- JDK1.8新特性(一) ----Lambda表达式、Stream API、函数式接口、方法引用
jdk1.8新特性知识点: Lambda表达式 Stream API 函数式接口 方法引用和构造器调用 接口中的默认方法和静态方法 新时间日期API default Lambda表达式 L ...
- 乐字节-Java8核心特性实战之函数式接口
什么时候可以使用Lambda?通常Lambda表达式是用在函数式接口上使用的.从Java8开始引入了函数式接口,其说明比较简单:函数式接口(Functional Interface)就是一个有且仅有一 ...
- java8学习之Supplier与函数式接口总结
Supplier接口: 继续学习一个新的函数式接口--Supplier,它的中文意思为供应商.提供者,下面看一下它的javadoc: 而具体的方法也是相当的简单,就是不接受任何参数,返回一个结果: 对 ...
- java代码之美(14)---Java8 函数式接口
Java8 函数式接口 之前写了有关JDK8的Lambda表达式:java代码之美(1)---Java8 Lambda 函数式接口可以理解就是为Lambda服务的,它们组合在一起可以让你的代码看去更加 ...
随机推荐
- IDC报告:阿里云领跑中国数据库市场年度份额首超传统厂商
简介: IDC报告显示,2020年中国关系型数据库软件市场规模达到121.8亿元,同比增长36.5%.其中,以公有云模式部署的关系型数据库市场占比达到51.5%,首次超过传统线下部署模式市场规模, ...
- [Cryptocurrency] okex 获取行情的三种方式, ticker、depth、kline
获取行情可以使用 ticker.depth.kline 这三种方式. ticker 得到的是最新一条的成交价行情数据记录. depth 得到的是指定条数的包含 成交价格 和 成交数量 的记录. kli ...
- WPF 布局 在有限空间内让两个元素尽可能撑开的例子
我在尝试写一个显示本机 WIFI 热点的账号和密码的控件,要求此控件在有限的空间内显示.但是尽可能显示出热点的账号和密码.而热点的账号和密码是用户配置的,也许长度很长.我的需求是在假如账号的长度较短的 ...
- 一个完整的可以输出移动端当前省市(地理坐标)的html页面
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 开源相机管理库Aravis例程学习(六)——camera-features
目录 简介 例程代码 函数说明 arv_camera_get_integer arv_camera_get_string 简介 本文针对官方例程中的:04-camera-features做简单的讲解. ...
- mod操作符效率高吗?
编程语言中mod取余操作符%的效率不是很高,比如M = N % 10,它花费得时间本机测试是1ms,而如果使用M = N - N / 10 * 10,则只需要0.1ms. 所以平时变成得时候,可以尽量 ...
- kkfileview搭建指南
最近公司有个需求,需要在线预览pdf,excel,world文档,pdf浏览器是直接支持预览的,vue也有很多插件支持,但是world文档和excel的方案就非常少了,市面上很多付费的,但是咱一般不舍 ...
- C数据结构线性表:最全链表实战剖析—单 双 循环链表&增删改查
文章目录 前言 说明1 说明2 A:关于为什么传链表要用二级指针 B:单链表 1:定义结构体 2:初始化链表 3:销毁链表内容 (释放整个链表空间,把L指针赋值为NULL ) 4:增加某一个位置上的元 ...
- C 语言编程 — 高级数据类型 — void 类型
目录 文章目录 目录 前文列表 void 类型 前文列表 <程序编译流程与 GCC 编译器> <C 语言编程 - 基本语法> <C 语言编程 - 基本数据类型> & ...
- pageOffice插件 springboot实现服务器上Word文档在线打开编辑保存
需求: 在oa系统上,想实现在线,服务器上doc,docx文档,在web打开,编辑.编辑后,可以再同步保存到服务器端. 开发环境: java springboot,thymeleaf 服务器环境: 无 ...