Common interface function
- Interfaces (not just one way) contains only an abstract method
- The interface is often associated with Lambda expressions
- Lambda expressions lazy loading, to avoid wasting performance
Supplier - Production Interface
java.util.function.Supplier <Generic t> contains only a non-parametric method of interfaces: T get (), used to obtain a generic parameter specifies the type of object data. Since this is a function interface, which means corresponding Lambda expressions need to "provide external" in line with a generic type of object data.
Supplier <> interface is called production interfaces, generic interface to specify what type, then the interface methods will get what type of data is produced, there is a return value.
package cn.learn;
import java.util.function.Supplier;
public class function {
//定义一个方法,方法参数传递Supplier<>接口,泛型执行String.get方法就会返回一个String
public static String getString(Supplier<String> stringSupplier){
return stringSupplier.get();
}
public static void main(String[] args) {
//调用getString方法,方法的参数是一个函数式表达接口,所以传递lambda表达式
String str = getString(() ->{
//生产一个字符串,并返回
return "aaa";
});
System.out.println(str);
//优化Lambda表达式
str = getString(() -> "aaa");
System.out.println(str);
}
}
Exercise: Find the maximum array elements
package cn.learn;
import java.util.function.Supplier;
public class function {
public static Integer getMax(Supplier<Integer> stringSupplier){
return stringSupplier.get();
}
public static void main(String[] args) {
//定义一个数组
int[] arr = new int[]{3,55,66,77,88,-5};
//调用getMax方法,使用Lambda表达式简写
int integermax = getMax(() ->{
//获取数组最大值并返回
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (max < arr[i]){
max = arr[i];
}
}
return max;
});
/******
//调用getMax方法
getMax(new Supplier<Integer>() {
@Override
public Integer get() {
//获取数组最大值并返回
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
return max;
}
});
*******/
System.out.println(integermax);
}
}
Consumer - Consumer Interface
java.util.function.Consumer <Generic> Supplier interfaces with interfaces exactly contrary, it is not a production data, a consumption data but that the data type is determined by the generic
Consumer interfaces include an abstract method void accept (T t), are intended consumption data is specified as a generic, non-return value
package cn.learn;
import java.util.function.Consumer;
public class function {
//accept方法接受的数据可以输出、计算等
public static void print(Integer year,Consumer<Integer> age){
age.accept(year);
}
public static void main(String[] args) {
//消费方式:直接输出
print(2018,(year) -> System.out.println("你的出生年是"+year));
//消费方式:反转字符串
print(2018,(year) -> {
String string = year.toString();
String re = new StringBuilder(string).reverse().toString();
System.out.println(re);
});
}
}
The default method --andThen Consumer methods
If a method parameters and return values are all Consumer types, then you can achieve: consumption data, the first thing to do an action, then do an operation, to achieve the combination, and this method is the default method Consumer interface
JDK source code
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
Note: java.util.Object of requireNonNull static method will take the initiative to throw a NullPointerException when abnormal parameter is null, which eliminates the need to write if statements and throws null pointer exception trouble.
To achieve the combined effect, two Lambda expressions can be, and semantics is andThen "step by step" operation, for example, the case of two steps in combination:
- Consumer <泛型string> con1;
Consumer <泛型string> con2;
String str = "hello";
con1.accept(str);
con2.accept(str);
- Consumer <泛型string> con1;
package cn.learn;
import java.util.function.Consumer;
public class function {
//把两个Consumer接口组合到一起,再对数据进行消费
public static void method(String str,Consumer<String> con1,Consumer<String> con2){
//使用原始方式
con1.accept(str);
con2.accept(str);
}
public static void main(String[] args) {
//原始使用方式,调用method方法,需要传递两个Lambda表达式
method("Hello",(str) -> {
//消费方式:转为大写
System.out.println(str.toUpperCase());
},(str) ->{
//消费方式:转为小写
System.out.println(str.toLowerCase());
});
}
}
- Then connecting the two interfaces consumption (who first, whoever consumption), may instead
con1.andThen (con2) .accept (str) ;
package cn.learn;
import java.util.function.Consumer;
public class function {
//andThen需要两个Consumer接口,可以把两个Consumer接口组合到一起,再对数据进行消费
public static void method(String str,Consumer<String> con1,Consumer<String> con2){
//先使用con1消费数据,再使用con2
con1.andThen(con2).accept(str);
}
public static void main(String[] args) {
//原始使用方式,调用method方法,需要传递两个Lambda表达式
method("Hello",(str) -> {
//消费方式:转为大写
System.out.println(str.toUpperCase());
},(str) ->{
//消费方式:转为小写
System.out.println(str.toLowerCase());
});
}
}
Exercise: formatted print information
package cn.learn;
import java.util.function.Consumer;
public class function {
//使用两个Consumer来消费字符串,泛型为字符数组
public static void method(String[] str,Consumer<String[]> con1,Consumer<String[]> con2){
//先使用con1消费数据,再使用con2
con1.andThen(con2).accept(str);
}
public static void main(String[] args) {
//定义一个字符串数组
String[] person ={"小王,男","大王,女"};
//原始使用方式,调用method方法,需要传递两个Lambda表达式
method(person,(str) -> {
//消费方式:取人名
for (String name:str) {
//取第一个元素
System.out.println(name.split(",")[0]);
}
},(str) ->{
//消费方式:取性别
for (String name:str) {
//取第一个元素
System.out.println(name.split(",")[1]);
}
});
}
}
Results:
Amy
King
Male
Female
- Another way
package cn.learn;
import java.util.function.Consumer;
public class function {
//使用两个Consumer来消费字符串,泛型为字符数组
public static void method(String[] str,Consumer<String> con1,Consumer<String> con2){
//将遍历写在此处,预防重复造轮子
for (String message:str) {
//先使用con1消费数据,再使用con2
con1.andThen(con2).accept(message);
}
}
public static void main(String[] args) {
//定义一个字符串数组
String[] person ={"小王,男","大王,女"};
//原始使用方式,调用method方法,需要传递两个Lambda表达式
method(person,(message) -> {
//消费方式:取人名
System.out.println(message.split(",")[0]);
},(message) ->{
//消费方式:取性别
System.out.println(message.split(",")[1]);
});
}
}
Results:
Wang
male
king
female
Predicate - judge Interface
Sometimes we need to be of a data type determination data, to thereby obtain the result of a boolean value, then you can use java.util.function.predicate <generic> Interface
Predicate interface contains an abstract method: boolean test (T t). Conditions for determining a scene, returns a Boolean value
```java
package cn.learn;
import java.util.function.Predicate;
public class function {
//
public static boolean checkMethod(String str, Predicate
return pre.test(str);
}
public static void main(String[] args) {
String str = "hello";
//对字符串进行校验
boolean check = checkMethod(str,(String str01) ->{
return str01.length()>5;
});
boolean check1 = checkMethod(str,str01 -> str01.length()>3);
System.out.println(check);
System.out.println(check1);
}
}
- The default method: and - can judge more judging condition and "&&" almost
package cn.learn;
import java.util.function.Predicate;
public class function {
//
public static boolean checkMethod(String str, Predicate<String> pre1, Predicate<String> pre2){
//等价于return pre1.test(str) && pre2.test(str);
return pre1.and(pre2).test(str);
}
public static void main(String[] args) {
String str = "hello";
//对字符串进行校验
boolean check = checkMethod(str,(String str01) ->{
return str01.length()>3;
},(str01) ->{
return str01.contains("1");
});
System.out.println(check);
}
}
false
- The default method: or - can determine multiple conditions and judgment "||" almost
package cn.learn;
import java.util.function.Predicate;
public class function {
//
public static boolean checkMethod(String str, Predicate<String> pre1, Predicate<String> pre2){
//等价于return pre1.test(str) || pre2.test(str);
return pre1.or(pre2).test(str);
}
public static void main(String[] args) {
String str = "hello";
//对字符串进行校验
boolean check = checkMethod(str,(String str01) ->{
return str01.length()>3;
},(str01) ->{
return str01.contains("1");
});
System.out.println(check);
}
}
true
- The default method: negate - can judge more judging condition and almost "!"
package cn.learn;
import java.util.function.Predicate;
public class function {
//
public static boolean checkMethod(String str, Predicate<String> pre1){
//等价于return !pre1.test(str);
return pre1.negate().test(str);
}
public static void main(String[] args) {
String str = "hello";
//对字符串进行校验
boolean check = checkMethod(str,(String str01) ->{
return str01.length()>3;
});
System.out.println(check);
}
}
false
Exercise: collection of information filtering
- The name is a string of two characters and female selected from the set, the string is determined need attention equals method
package cn.learn;
import java.util.ArrayList;
import java.util.function.Predicate;
public class function {
public static ArrayList<String> filter(String[] str, Predicate<String> pre1, Predicate<String> pre2) {
//放外边,里边会重复申请
ArrayList<String> correct = new ArrayList<>();
//遍历数组
for (String message : str) {
boolean ifCorr = pre1.and(pre2).test(message);
//满足条件的放入集合
if (ifCorr) {
correct.add(message);
}
}
return correct;
}
public static void main(String[] args) {
String[] str = {"小王,女", "大王,男", "小白,男", "王小白,女"};
//对字符串进行筛选,并返回需要的集合
ArrayList<String> list = filter(str, (String str01) -> {
return str01.split(",")[0].length() == 2;
}, (str01) -> str01.split(",")[1].equals("女") );
System.out.println(list);
}
}
[Wang, female]
Function - Data type conversion interface
java.util.function.Function <T, R> interface is used to obtain a data type to another data type The former is called pre-conditions, which is referred to as post-conditions.
Abstract methods: apply, R apply
Obtain result R type according to the parameters of type T, it returns the value of another type.
package cn.learn;
import java.util.function.Function;
public class function {
public static Integer convert(String str, Function<String,Integer> function){
//返回一个Integer类型
return function.apply(str);
}
public static void main(String[] args) {
String str = "2018";
//调用convert方法转换类型,并用Lambda表达式重写apply方法
Integer strInt = convert(str,(String str01) ->{
return Integer.parseInt(str01);
});
System.out.println(strInt);
}
}
Default method: andThen, used for combining operation
Demand: convert string type Integer, the result of calculation,
then converted back Integer
package cn.learn;
import java.util.function.Function;
public class function {
public static String convert(String str, Function<String,Integer> fun1,Function<Integer,String> fun2){
//返回一个String类型
return fun1.andThen(fun2).apply(str);
}
public static void main(String[] args) {
String str = "2018";
//调用convert方法转换类型,取出字符串对应的值并进行运算,再转换为String
str = convert(str,str01 ->Integer.parseInt(str01)+10,int01 -> int01.toString());
System.out.println(str);
}
}
2028