学习笔记
import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.junit.Test;
import com.it.entity.Employee;
public class TestLambda4 {
@Test
public void test1() {
PrintStream ps1 = System.out;
Consumer<String> con = (x) -> ps1.println(x);
PrintStream ps2 = System.out;
Consumer<String> con1 = ps2::println;
Consumer<String> con2 = System.out::println;
con2.accept("aabbcc");
}
@Test
public void test2() {
Employee emp = new Employee();
Supplier<String> sup = () -> emp.getName();
String name = sup.get();
System.out.println(name);
Supplier<Integer> sup2 = emp::getAge;
System.out.println(sup2.get());
}
@Test
public void test3() {
Comparator<Integer> com = (x,y) -> Integer.compare(x, y);
Comparator<Integer> com2 = Integer::compare;
}
@Test
public void test4() {
BiPredicate<String, String> bp = (x,y) -> x.equals(y);
BiPredicate<String, String> bp2 = String::equals;
}
@Test
public void test5() {
Supplier<Employee> sup = () -> new Employee();
Supplier<Employee> sup2 = Employee::new;
Employee emp = sup2.get();
System.out.println(emp);
}
@Test
public void test6() {
Function<Integer,Employee> fun = (x) -> new Employee(x);
Function<Integer,Employee> fun2 = Employee::new;
}
}
案例
- 数组的引用
@Test
public void test7() {
Function<Integer,String[]> fun = (x) -> new String[x];
String[] strs = fun.apply(10);
System.out.println(strs.length);
Function<Integer,String[]> fun2 = String[]::new;
String[] strs2 = fun2.apply(20);
System.out.println(strs2.length);
}