package com.zyh.java8;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.function.Function;
import java.util.function.Supplier;
import org.junit.Test;
import com.zyh.pojo.Employee;
/**
* 方法引用本质上使用一种现场的方法简写方式来作为匿名内部类的一种实现
* lambda表达式 方法引用 要求:方法的参数要和函数式接口的参数和返回值类型数目一致才可以
*
* 1.类名::静态方法名
* 2.类名::实例方法名 当实例方法的调用者为第一个参数时 可以这样用
* 3.对象的引用::实例方法名
*
* 构造器引用 构造器的参数列表需要与函数式接口中的参数列表保持一致
* 1.类名::new
*
* 数组引用:类型[]::new
*
* @author Administrator
*
*/
public class LambdaTest04 {
@Test
public void test09() {
Function<Integer, String[]> function=args->new String[args];
String[] strings=function.apply(10);
System.out.println(strings.length);
Function<Integer, Employee[]> function2=Employee[]::new;
Employee[] employees=function2.apply(20);
System.out.println(employees.length);
}
/**
* 调用一个参数的构造器
*/
@Test
public void test08() {
Function<String, Employee> function=Employee::new;
System.out.println(function.apply("李刚").getName());
}
/**
* 调用无参构造器
*/
@Test
public void test07() {
Supplier<Employee> supplier=()->new Employee();
System.out.println(supplier.get());
Supplier<Employee> supplier2=Employee::new;
System.out.println(supplier2.get());
}
/**
* boolean test(T t, U u); boolean equals(Object anObject)
*/
@Test
public void test06() {
BiPredicate<String,String> bPredicate=String::equals;
boolean b=bPredicate.test("abc","abc");
System.out.println(b);
}
/**
* R apply(T t); String trim()
*/
@Test
public void test05() {
String string=" abcdefg ";
Function<String, String> function=String::trim;
String string2=function.apply(string);
System.out.println(string2);
}
/**
* T get(); String getName()
*/
@Test
public void test04() {
Employee employee=new Employee("zhangsan",20);
Supplier<String> supplier=employee::getName;
System.out.println(supplier.get());
}
/**
* 类名::实例方法名
*/
@Test
public void test03() {
BiPredicate<String,String> bPredicate=(x,y)->x.equals(y);
System.out.println(bPredicate.test("abcde", "abcde"));
BiPredicate<String,String> bPredicate2=String::equals;
System.out.println(bPredicate2.test("abc", "abc"));
}
/**
* 类名::静态方法名引用 int compare(T o1, T o2); int compare(int x, int y)
*/
@Test
public void test01() {
Comparator<Integer> comparator=(x,y)->Integer.compare(x, y);
comparator.compare(15, 20);
Comparator<Integer> comparator2=Integer::compare;
}
/**
* 静态方法引用示例
* R apply(T t); T max(Collection<T> coll)
*/
@Test
public void test02() {
Function<List<Integer>,Integer> maxFn=Collections::max;
Integer max=maxFn.apply(Arrays.asList(1,10,3,5,6));
System.out.println(max);
}
}