函数式接口

函数式接口详解:FunctionInterface接口

话不多说,先打开源码,查阅一番。寻得FunctionInterface接口

package java.util.function;

import java.util.Objects;

/**
* Represents a function that accepts one argument and produces a result.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #apply(Object)}.
*
* @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); /**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null
*
* @see #andThen(Function)
*/
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
} /**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*
* @see #compose(Function)
*/
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
} /**
* Returns a function that always returns its input argument.
*
* @param <T> the type of the input and output objects to the function
* @return a function that always returns its input argument
*/
static <T> Function<T, T> identity() {
return t -> t;
}
}

函数式接口代码测试:FunctionTest

public class FunctionTest {
public static void main(String[] args) {
FunctionTest test = new FunctionTest();
// 传递行为,而不是传递值
System.out.println(test.comput(1, value -> 2 * value)); System.out.println(test.comput(2, value -> 5 + value)); System.out.println(test.comput(3,Integer::intValue)); System.out.println(test.convert(4,value -> value + "helloworld"));
} public int comput(int a, Function<Integer, Integer> function) {
//apply ,传递的是行为
int result = function.apply(a);
return result;
} public String convert(int a, Function<Integer, String> function) {
return function.apply(a);
} // 对于之前只传递值的写法,几种行为就要定义几种写法。 现在可以使用上面的方式去 传递行为
public int method1(int a) {
return a + 1;
} public int method2(int a) {
return a * 5;
} public int method3(int a) {
return a * a;
}
}

高阶函数:如果一个函数接收一个函数作为参数,或者返回一个函数作为返回值,那么该函数就叫做高阶函数。函数式编程语言js等语言里面都支持大量的高阶函数,JAVA从1.8开始也开始支持高阶函数。

FunctionInterface接口中提供的方法详解

  1. apply
  2. compose (function组合)
  3. andThen
  4. identity

代码测试上述方法

package java.util.function;

import java.util.Objects;

/**
* Represents a function that accepts one argument and produces a result.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #apply(Object)}.
*
* @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); /**
* Returns a composed function that first applies the {@code before}
* function to its input, and then applies this function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of input to the {@code before} function, and to the
* composed function
* @param before the function to apply before this function is applied
* @return a composed function that first applies the {@code before}
* function and then applies this function
* @throws NullPointerException if before is null * 先应用beforefunction,再应用实例的function
实际上:将两个function组合在一起了。先执行before方法,然后将处理的结果传递给当前对象的apply方法。实现了两个function的串联。既然实现了两个function的串联,就能实现多个函数的串联。
* @see #andThen(Function)
*/
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
} /**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null 和before函数相反,先应用this function,然后再使用after方法。 实现两个方法的串联。 * @see #compose(Function)
*/
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
} /**
* Returns a function that always returns its input argument.
*
* @param <T> the type of the input and output objects to the function
* @return a function that always returns its input argument
*/
static <T> Function<T, T> identity() {
return t -> t;
}
}
  • compose:

    先应用beforefunction,再应用实例的function

    实际上:将两个function组合在一起了。先执行before方法,然后将处理的结果传递给当前对象的apply方法。实现了两个function的串联。既然实现了两个function的串联,就能实现多个函数的串联。
  • andThen:

    和before函数相反,先应用this function,然后再使用after方法。 实现两个方法的串联。
  • identity:

    传入什么,返回什么。

这些方法都是很有价值的。

/**
* compose , andThen 方法的使用
*/
public class FunctionTest2 { public static void main(String[] args) {
FunctionTest2 test2 = new FunctionTest2();
int compute = test2.compute(2, v -> v * 3, v -> v * v);//12
int compute2 = test2.compute2(2, v -> v * 3, v -> v * v);//36
System.out.println(compute);
System.out.println(compute2);
} public int compute(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.compose(function2).apply(a);
}
public int compute2(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.andThen(function2).apply(a);
}
}

BiFunction类详解

package java.util.function;

import java.util.Objects;

/**
* Represents a function that accepts two arguments and produces a result.
* This is the two-arity specialization of {@link Function}.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #apply(Object, Object)}.
*
* @param <T> the type of the first argument to the function
* @param <U> the type of the second argument to the function
* @param <R> the type of the result of the function
*
* @see Function
* @since 1.8
*/
@FunctionalInterface
public interface BiFunction<T, U, R> { /**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u); /**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*/
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(apply(t, u));
}
}

BiFunction类,双向接口类,提供了两个输入参数,一个输出参数

    //BiFunction类的使用。 有两个输入参数
public int compute3(int a, int b, BiFunction<Integer, Integer, Integer> biFunction) {
return biFunction.apply(a, b);
} public int compute4(int a, int b, BiFunction<Integer, Integer, Integer> biFunction,Function<Integer,Integer> function) {
return biFunction.andThen(function).apply(a,b);
} //使用BiFunction来完成
System.out.println(test2.compute3(1,2,(value1,value2)-> value1 + value2));
System.out.println(test2.compute3(1,2,(value1,value2)-> value1 - value2));
System.out.println(test2.compute3(1, 2, (value1, value2) -> value1 * value2));
System.out.println(test2.compute3(1, 2, (value1, value2) -> value1 / value2)); //使用BiFunction中的andThen.
System.out.println(test2.compute4(2,3,(value1,value2)->value1+value2,value->value*value));

为什么BiFunction类中没有Compose方法呢?

倒推一下:因为如果有Compose方法,会先执行参数的Function。无论参数是Function还是BiFunction,返回值也都是一个值,然后就没办法再去执行BiFuntion.


使用lambda表达式解决简单的开发问题:

定义一个简单的Person类,然后使用lambda表达式解决一些问题
public class Person {
private String username;
private int age;
}
package com.dawa.jdk8;

import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
import java.util.stream.Collectors; public class PersonTest {
public static void main(String[] args) { Person person1 = new Person("zhangsan", 20);
Person person2 = new Person("lisi", 30);
Person person3 = new Person("wangwu", 40); List<Person> list = Arrays.asList(person1,person2,person3); PersonTest test = new PersonTest();
//测试第一个方法。
List<Person> list1 = test.getPersonByUsername("zhangsan", list);
list1.forEach(person -> System.out.println(person.getUsername()));
//测试第二种方法
List<Person> personByAge = test.getPersonByAge(20, list);
personByAge.forEach(person -> System.out.println(person.getAge()));
//测试第三方法
List<Person> peopleList = test.getPersonByArg(20, list,
(age, personList) -> personList.stream().filter(p
erson -> person.getAge() > age).collect(Collectors.toList()));
peopleList.forEach(person -> System.out.println(person.getUsername())); } //使用lambda表达式定义一个 处理的方法
//filter 方法,参数是一个Predicate 谓语
//stream 提供了一个将流转换成集合的方法 collect(Collectors.toList())
public List<Person> getPersonByUsername(String username, List<Person> personList) {
return personList.stream().
filter(person ->
person.getUsername().equals("zhangsan")).collect(Collectors.toList());
} //第二种方式,先直接使用lambda表达式将BiFunction定义好,然后直接将方法的两个参数传入到BiFunction.
public List<Person> getPersonByAge(int age, List<Person> personList) {
BiFunction<Integer, List<Person>, List<Person>> biFunction = (ageArg, Persons) -> {
return Persons.stream().filter(person -> person.getAge() > ageArg).collect(Collectors.toList());
};
return biFunction.apply(age,personList);
} //第三种方式,动作也让他自己传递。 函数式接口的好处。
public List<Person> getPersonByArg(int age, List<Person> personList, BiFunction<Integer, List<Person>, List<Person>> biFunction) {
return biFunction.apply(age, personList);
}
}

真谛:函数式接口,传递的是行为,而不是数据。

Predicate 类详解(谓词)

package java.util.function;

import java.util.Objects;

/**
* Represents a predicate (boolean-valued function) of one argument.
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #test(Object)}.
*
* @param <T> the type of the input to the predicate
*
* @since 1.8
*/
@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); /**
* Returns a composed predicate that represents a short-circuiting logical
* AND of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code false}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ANDed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* AND of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
} /**
* Returns a predicate that represents the logical negation of this
* predicate.
*
* @return a predicate that represents the logical negation of this
* predicate
*/
default Predicate<T> negate() {
return (t) -> !test(t);
} /**
* Returns a composed predicate that represents a short-circuiting logical
* OR of this predicate and another. When evaluating the composed
* predicate, if this predicate is {@code true}, then the {@code other}
* predicate is not evaluated.
*
* <p>Any exceptions thrown during evaluation of either predicate are relayed
* to the caller; if evaluation of this predicate throws an exception, the
* {@code other} predicate will not be evaluated.
*
* @param other a predicate that will be logically-ORed with this
* predicate
* @return a composed predicate that represents the short-circuiting logical
* OR of this predicate and the {@code other} predicate
* @throws NullPointerException if other is null
*/
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
} /**
* Returns a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}.
*
* @param <T> the type of arguments to the predicate
* @param targetRef the object reference with which to compare for equality,
* which may be {@code null}
* @return a predicate that tests if two arguments are equal according
* to {@link Objects#equals(Object, Object)}
*/
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}

默认调用:boolean test(T t)给定一个输入参数,判断是否满足条件。满足则返回true,不满足返回false。

测试案例:

package com.dawa.jdk8;

import java.util.function.Predicate;

public class PreDicateTest {
public static void main(String[] args) {
Predicate<String> predicate = p -> p.length() > 5; System.out.println(predicate.test("hello")); }
}

这个接口会在流stream里面得到大量的运用。上述案例在 stream的 filter()方法参数中使用。

到现在为止,Function包下的接口已经基础了两个了。

可是只是讲了几个特别重要的接口,其他的接口是没时间一个一个讲的。

这个时候我去看了一下源码,发现JAVA8底层源码,大量的使用函数接口来进行实现。

道阻且长。~ 加油。

2019年12月29日22:18:25。明天就要上班了,今晚早点休息。

JAVA8学习——深入浅出函数式接口FunctionInterface(学习过程)的更多相关文章

  1. JAVA8学习——深入浅出Lambda表达式(学习过程)

    JAVA8学习--深入浅出Lambda表达式(学习过程) lambda表达式: 我们为什么要用lambda表达式 在JAVA中,我们无法将函数作为参数传递给一个方法,也无法声明返回一个函数的方法. 在 ...

  2. Java8 学习笔记--函数式接口

    通过之前的函数式接口与lambda表达式的关系那篇文章,大家应该对函数式接口有了一定的了解了,在Java中它是lambda表达式的基础,没有函数式接口就没有办法使用lambda表达式. 函数式接口如此 ...

  3. Java8 学习笔记--函数式接口与lambda表达式的关系

    在java中,lambda表达式与函数式接口是不可分割的,都是结合起来使用的. 对于函数式接口,我们可以理解为只有一个抽象方法的接口,除此之外它和别的接口相比并没有什么特殊的地方.为了确保函数式接口的 ...

  4. java8新特性学习:函数式接口

    本文概要 什么是函数式接口? 如何定义函数式接口? 常用的函数式接口 函数式接口语法注意事项 总结 1. 什么是函数式接口? 函数式接口其实本质上还是一个接口,但是它是一种特殊的接口:SAM类型的接口 ...

  5. java基础---->java8中的函数式接口

    这里面简单的讲一下java8中的函数式接口,Function.Consumer.Predicate和Supplier. 函数式接口例子 一.Function:接受参数,有返回参数 package co ...

  6. Java8 新特性 函数式接口

    什么是函数式接口   函数式接口是Java8引用的一个新特性,是一种特殊的接口:SAM类型的接口(Single Abstract Method).但是它还是一个接口,只是有些特殊罢了.  函数式接口的 ...

  7. Java8 新特性----函数式接口,以及和Lambda表达式的关系

    这里来讲解一下Java8 新特性中的函数式接口, 以及和Lambda 表达式的关系.看到过很多不少介绍Java8特性的文章,都会介绍到函数式接口和lambda表达式,但是都是分别介绍,没有将两者的关系 ...

  8. JAVA8学习——深入Comparator&Collector(学习过程)

    深入Comparator&Collector 从源码深入Comparator Comparator从Java1.2就出来了,但是在1.8的时候,又添加了大量的默认方法. compare() e ...

  9. java8中使用函数式接口

    使用函数式接口 Predicate @FunctionalInterface interface Predicate<T>{ boolean test(T t); } public sta ...

随机推荐

  1. 《C程序设计语言》笔记(三)

    六:结构 1:结构体声明中,比如: struct point{ int x; int y; }; struct后面的名字是可选的,称为结构标记.结构成员.结构标记和普通变量可以采用相同的名字,它们之间 ...

  2. 根据花瓶的侧面投影图,用Matlab绘制花瓶的三维立体图

    现有一花瓶侧面投影如图 问题: 1)    做出该花瓶三维立体图: 2)    计算其表面积:  计算其体积. 第一次参加数学建模,从来没有接触过Matlab语言,一上来就碰到这种数字图像处理的问题就 ...

  3. Python基础:24with语句

    一:with语句 在Python 2.6 中正式引入的with语句,是用来简化代码的.这与用try-except 和try-finally所想达到的目的前后呼应.try-except 和try-fin ...

  4. HDU3844 Mining Your Own Business

    HDU3844 Mining Your Own Business 问题描述John Digger是一个大型illudium phosdex矿的所有者.该矿山由一系列隧道组成,这些隧道在各个大型交叉口相 ...

  5. PHP中__FUNCTION__与__METHOD__的区别

    你知道php中__FUNCTION__与__METHOD__的区别吗?本文通过一个小例子,为大家介绍下二者的区别,有兴趣的朋友可以参考下.   PHP中__FUNCTION__与__METHOD__的 ...

  6. JQuery完整验证&密码的显示与隐藏&验证码

    HTML <link href="bootstrap.css" rel="stylesheet"> <link href="gloa ...

  7. java一般处理高并发的技术手段

    应对高并发的解决方案: 1.将压力放在数据库上面,添加行级锁. select * from table for update; 2.将压力放在应用程序上面,对方法加synchronized同步.

  8. C++ 结构体的定义

    struct 结构体名称{    数据类型 A:    数据类型 B; }结构体变量名; 相当于: struct 结构体名称{    数据类型 A:    数据类型 B; }; struct 结构体名 ...

  9. LRJ-Example-06-01-Uva210

    #define _CRT_SECURE_NO_WARNINGS #include <cstdio> #include <cstdlib> #include <cstrin ...

  10. yeoman&bower

    一.Yeoman 在nodejs环境下安装: npm install -g yo 然后安装所需要的generator,generator是npm包,命名为generator-xyz,比如安装angul ...