1.java8原生的函数型接口(一些子类有特殊的应用场景,用法类似,小胖这里就不列举了)
/**
* @ClassName JavaMain
* @Description 测试java8原生的函数型接口. 欢迎加337045684 一起交流成长,进步
* @Author 勤小胖
* @Date 2018/12/28 14:45
**/
public class JavaMain {
/**
* Consumer 消费性接口
*/
@Test
public void test() {
//个人对消费型接口Consumer的理解:传入的参数会直接输出到控制台,而不做任何处理的操作
Consumer<String> con = (x) -> System.out.println("当前的操作者是:" + x);
con.accept("张三");
}
/**
* 供给型接口
*/
@Test
public void test1() {
//Supplier:利用lamda表达式对方法T get()进行实现,然后调用get()返回Object
Person person = new Person();
Supplier<String> supplier = () -> person.getName();
System.out.println(supplier.get());
}
/**
* 函数型接口
*/
@Test
public void test2() {
//Function:传入参数,并返回一个对象的操作
//1.操作对象
Function<String, Person> function = (str) -> new Person(str);
Person p = function.apply("张三");
System.out.println(p);
//2.操作string
Function<String,String> function1 = (str) -> str.trim();
System.out.println("-----------去除空格操作-------------");
String newString= function1.apply("\t\t\t\t\t\t\t小胖子又来搬砖了");
System.out.println(newString);
}
/**
* 断言型接口
*/
@Test
public void test3(){
//该接口应用于条件过滤操作,大大优化于1.7的操作
Predicate<Person> predicate = (con) -> con.getAge() > 35;
boolean isFlag = predicate.test(new Person("张三",45));
System.out.println(isFlag);
}
}
2.java8引入新的语法-------------方法引用
- 对象-实例方法
@Test
public void test() {
//lamda方式
Consumer<String> con = (x) -> System.out.println("输出到控制台:" + x);
/**
* 方法引用
* 通过对象可以直接调用实例方法实现消费型接口 accept(T t)
*/
PrintStream ps = System.out;
Consumer<String> con1 = (x) -> ps.print("输出到控制台" + x);
//在java8 可以将上面的代码转变为下面代码
Consumer<String> con2 = ps::println;
//调用方法 并且输出到控制台
con2.accept("1234");
}
- 类-静态方法
@Test
public void test3() {
//lamda
Comparator<Integer> c = (x, y) -> Integer.compare(x, y);
System.out.println(c.compare(6, 3));
//方法引用
Comparator<Integer> c1 = Integer::compare;
System.out.println(c1.compare(12,34));
}
- 类-实例方法
@Test
public void test4() {
//lamda
BiPredicate<String, String> biPredicate = (x, y) -> x.equals(y);
//方法引用
BiPredicate<String, String> biPredicate1 = String::equals;
System.out.println(biPredicate.test("1", "1"));
}
- 构造器引用
@Test
public void test5() {
//lamda
Supplier<Car> supplier = () -> new Car();
//调用参数为空的构造器
Supplier<Car> supplier1 = Car::new;
//调用参数列表是一个的构造器
Function<String,Car> function = Car::new;
}
- 数组引用
@Test
public void test6(){
Function<Integer,String[]> function1 = (x) -> new String[x];
Function<Integer,String[]> function2 = String[]::new;
String[] str = function2.apply(20);
System.out.println(str.length);
}
小胖在成长的路上,只信一句话量变引起质变,知识重在积累,欢迎大家指出文章不足之处,谢谢各位
欢迎加入勤小胖的qq群: