Java8笔记一

1、在接口方面的变化

Java8对接口的改变:
①增加了default方法和static方法,这两种方法完全可以有方法体。
②default方法属于实例,static方法属于类(接口)。
③接口里面的静态方法不会被继承。静态变量会被继承下来。

2、Lambda表达式

函数式接口:当接口里面只有一个抽象方法的时候,就是函数式接口,可以使用注解强制限定接口只能有一个抽象方法。
注解:从Java5开始引入注解。利用注解对字节码文件进行一些说明。
@FunctionalInterface 注解的作用是用于在编译时告诉编译器该接口只能有一个抽象方法。

3、为什么使用Lambda表达式

  Lambda是一个匿名函数,可以把Lambda表达式理解为是一段可以传递的代码(将代码像数据一样传递)

//创建实体类
public class Employee {
    private String name;
    private int age;
    private double salary;

    //无参构造器
    public Employee() {
    }

    //全参构造器
    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}
public interface MyPredicate<T> {

    boolean test(T t);
}
public class FilterEmployeeByAge implements MyPredicate<Employee> {
    @Override
    public boolean test(Employee t){
        return t.getAge() >= 20;
    }
}
import java.util.*;
import org.junit.Test;

public class TestLambda {

    /**
     * 原来的匿名内部类
     * */
    @Test
    public void test1(){
        Comparator<Integer> com = new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return Integer.compare(o1, o2);
            }
        };
        TreeSet<Integer> ts = new TreeSet<>(com);
    }

    /**
     * Lambda表达式
     * */
    @Test
    public void test2(){
        Comparator<Integer> com = (x,y) -> Integer.compare(x, y);
        TreeSet<Integer> ts = new TreeSet<>(com);
    }

    List<Employee> employees = Arrays.asList(
            new Employee("张三",18,6666.66),
            new Employee("里斯",23,9999.99)
    );

    /**
     *  需求:获取当前员工年龄大于20的员工信息
     **/
    @Test
    public void test3(){
        List<Employee> list = filterEmployees(employees);
        for(Employee employee : list){
            System.out.println(employee);
        }
    }
    public List<Employee> filterEmployees(List<Employee> list){
        List<Employee> emps = new ArrayList<>();

        for(Employee emp : list){
            if(emp.getAge() >= 20){
                emps.add(emp);
            }
        }
        return emps;
    }

    /**
     * 优化一:策略设计模式
     */
    @Test
    public void test4(){
        List<Employee> list = filterEmployee(employees,new FilterEmployeeByAge());
        for(Employee employee : list){
            System.out.println(employee);
        }
    }

    public List<Employee> filterEmployee (List<Employee> list,MyPredicate<Employee> mp){
        List<Employee> emps = new ArrayList<>();
        for (Employee employee : list){
            if(mp.test(employee)){
                emps.add(employee);
            }
        }
        return emps;
    }

    /**
     * 优化二:Lambda表达式
     */
    @Test
    public void test5(){
        List<Employee> list = filterEmployee(employees,(e) -> e.getAge() >= 20);
        list.forEach(System.out::print);
    }

    /**
     * 优化三: Stream API
     */
    @Test
    public void test6(){
        employees.stream()
                .filter((e) -> e.getAge() >= 20)
                .forEach(System.out::print);

        employees.stream()
                .map(Employee::getName)
                .forEach(System.out::print);
    }
}

 4、Lambda基础语法

Lambda 表达式在Java 语言中引入了一个新的语法元素和操作符。这个操作符为 “->” , 该操作符被称为 Lambda 操作符或剪头操作符。它将 Lambda 分为两个部分:
左侧:指定了 Lambda 表达式需要的所有参数
右侧:指定了 Lambda 体,即 Lambda 表达式要执行的功能。
①语法格式一:无参,无返回值,Lambda 体只需一条语句

Runnable r1 = () -> System.out.println("Hello Lambda!");

②Lambda 只需要一个参数时,参数的小括号可以省略

Consumer<String> fun = args -> System.out.println(args);

③Lambda 需要两个参数,并且有返回值

BinaryOperator<Long> bo = (x,y) -> {
    System.out.println("实现函数接口方法!");
    return x+y;
};

④当 Lambda 体只有一条语句时,return 与大括号可以省略

BinaryOperator<Long> bo = (x,y) -> x+y;

⑤数据类型可以省略,因为可由编译器推断得出,称为“类型推断”

BinaryOperator<Long> bo = (Long x, Long y) -> {
    System.out.println("实现函数接口方法!");
    return x+y;
};

5、函数式接口

Lambda 表达式需要“函数式接口”的支持;

示例:①声明一个带两个泛型的函数式接口,泛型类型为<T,R>  T为参数,R为返回值
②接口中声明对应抽象方法
③在TestLambda类中声明方法,使用接口作为参数,计算两个long型参数的和
④再计算两个long型参数的乘积

//声明接口
public interface MyFunction2<T, R> {
    public R getValue(T t1, T t2);
}

//创建TestLambda类
public class TestLambda {
    @Test
    public void test3(){
        op(100L, 200L, (x, y) -> x + y);
        op(100L, 200L, (x, y) -> x * y);
     }

    /**
     * 需求:对于两个 Long 型数据进行处理
     */
     public void op(Long n1, Long n2, MyFunction2<Long, Long> mf){
         System.out.println(mf.getValue(n1, n2));
      }
}

函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解@FunctionalInterface 修饰,可以检查是否是函数式接口
①自定义函数式接口

@FunctionalInterface
public interface MyNumber{
    public double getValue();
}

②函数式接口中使用泛型

@FunctionalInterface
public interface MyFunc<T>{
    public T getValue(T t);
} 

//作为参数传递 Lambda 表达式
public String toUpperString(MyFunc<String> mf, String str){
    return mf.getValue(str);
}

//作为参数传递 Lambda 表达式:
String newStr = toUpperString(
    (str) -> str.toUpperCase(), "abcdef");
System.out.println(newStr);    

作为参数传递 Lambda 表达式:为了将 Lambda 表达式作为参数传递,接收Lambda 表达式的参数类型必须是与该 Lambda 表达式兼容的函数式接口的类型。

6、Java8 内置的四大核心函数式接口

public class TestLambda3 {

    //Predicate<T> 断言型接口:
    @Test
    public void test4(){
        List<String> list = Arrays.asList("Hello", "Lambda", "www", "ok");
        List<String> strList = filterStr(list, (s) -> s.length() > 3);

        for (String str : strList) {
            System.out.println(str);
        }
    }

    //需求:将满足条件的字符串,放入集合中
    public List<String> filterStr(List<String> list, Predicate<String> pre){
        List<String> strList = new ArrayList<>();

        for (String str : list) {
            if(pre.test(str)){
                strList.add(str);
            }
        }

        return strList;
    }

    //Function<T, R> 函数型接口:
    @Test
    public void test3(){
        String subStr = strHandler("北京欢迎你!", (str) -> str.substring(2, 5));
        System.out.println(subStr);
    }

    //需求:用于处理字符串
    public String strHandler(String str, Function<String, String> fun){
        return fun.apply(str);
    }

    //Supplier<T> 供给型接口 :
    @Test
    public void test2(){
        List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));

        for (Integer num : numList) {
            System.out.println(num);
        }
    }

    //需求:产生指定个数的整数,并放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> sup){
        List<Integer> list = new ArrayList<>();

        for (int i = 0; i < num; i++) {
            Integer n = sup.get();
            list.add(n);
        }

        return list;
    }

    //Consumer<T> 消费型接口 :
    @Test
    public void test1(){
        happy(10000, (m) -> System.out.println("去购物,每次消费:" + m + "元"));
    }

    public void happy(double money, Consumer<Double> con){
        con.accept(money);
    }
}

7、方法引用与构造器引用

⑴、方法引用
当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!
实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致!

方法引用所引用的方法的参数列表与返回值类型,
需要与函数式接口中抽象方法的参数列表和返回值类型保持一致
//类名 :: 静态方法名
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
//lambda体中的compare方法的参数列表和返回值类型,
//要与函数式接口Comparator<Integer>中的抽象方法的参数列表和返回值类型保持一致
Comparator<Integer> com2 = Integer::compare;

方法引用:使用操作符”::“将方法名和对象或类的名字分隔开来
如下三种主要使用情况:
①对象::实例方法
②类::静态方法
③类::实例方法

(x) -> System.out.println(x);
等同于:
System.out::println

BinaryOperator<Double> bo = (x,y) -> Math.pow(x,y);
等同于:
BinaryOperator<Double> bo = Math::pow;
compare((x,y) -> x.equals(y), "abcdef", "abcdef");
等同于:
compare(String::equals, "abc", "abc");
若Lambda 的参数列表的第一个参数,是实例方法的调用者,
第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName

注意:当需要引用方法的第一个参数是调用对象,并且第二个参数是需要引用方法的第二个参数(或无参数)时:ClassName::methodName
⑵、构造器引用
格式: ClassName::new
构造器的参数列表,需要与函数式接口中参数列表保持一致

Function<Integer, MyClass> fun = (n) -> new MyClass(n);
等同于
Function<Integer, MyClass> fun = MyClass::new; 

⑶、数组引用
格式: type[] :: new

Function<Integer, Integer[]> fun = (n) -> new Integer[n];
等同于
Function<Integer, Integer[]> fun = Integer[]::new;
/**
 * 一、方法引用:若 Lambda 体中的功能,已经有方法提供了实现,可以使用方法引用
 *             (可以将方法引用理解为 Lambda 表达式的另外一种表现形式)
 *
 * 1. 对象的引用 :: 实例方法名
 *
 * 2. 类名 :: 静态方法名
 *
 * 3. 类名 :: 实例方法名
 *
 * 注意:
 *      ①方法引用所引用的方法的参数列表与返回值类型,需要与函数式接口中抽象方法的参数列表和返回值类型保持一致!
 *      ②若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: ClassName::MethodName
 *
 * 二、构造器引用 :构造器的参数列表,需要与函数式接口中参数列表保持一致!
 *
 * 1. 类名 :: new
 *
 * 三、数组引用
 *
 *     类型[] :: new;
 *
 *
 */
public class TestMethodRef {
    //数组引用
    @Test
    public void test8(){
        Function<Integer, String[]> fun = (args) -> new String[args];
        String[] strs = fun.apply(10);
        System.out.println(strs.length);

        System.out.println("--------------------------");

        Function<Integer, Employee[]> fun2 = Employee[] :: new;
        Employee[] emps = fun2.apply(20);
        System.out.println(emps.length);
    }

    //构造器引用
    @Test
    public void test7(){
        Function<String, Employee> fun = Employee::new;

        BiFunction<String, Integer, Employee> fun2 = Employee::new;
    }

    @Test
    public void test6(){
        Supplier<Employee> sup = () -> new Employee();
        System.out.println(sup.get());

        System.out.println("------------------------------------");

        Supplier<Employee> sup2 = Employee::new;
        System.out.println(sup2.get());
    }

    //类名 :: 实例方法名
    @Test
    public void test5(){
        BiPredicate<String, String> bp = (x, y) -> x.equals(y);
        System.out.println(bp.test("abcde", "abcde"));

        System.out.println("-----------------------------------------");

        BiPredicate<String, String> bp2 = String::equals;
        System.out.println(bp2.test("abc", "abc"));

        System.out.println("-----------------------------------------");


        Function<Employee, String> fun = (e) -> e.show();
        System.out.println(fun.apply(new Employee()));

        System.out.println("-----------------------------------------");

        Function<Employee, String> fun2 = Employee::show;
        System.out.println(fun2.apply(new Employee()));

    }

    //类名 :: 静态方法名
    @Test
    public void test4(){
        Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

        System.out.println("-------------------------------------");

        Comparator<Integer> com2 = Integer::compare;
    }

    @Test
    public void test3(){
        BiFunction<Double, Double, Double> fun = (x, y) -> Math.max(x, y);
        System.out.println(fun.apply(1.5, 22.2));

        System.out.println("--------------------------------------------------");

        BiFunction<Double, Double, Double> fun2 = Math::max;
        System.out.println(fun2.apply(1.2, 1.5));
    }

    //对象的引用 :: 实例方法名
    @Test
    public void test2(){
        Employee emp = new Employee(101, "张三", 18, 9999.99);

        Supplier<String> sup = () -> emp.getName();
        System.out.println(sup.get());

        System.out.println("----------------------------------");

        Supplier<String> sup2 = emp::getName;
        System.out.println(sup2.get());
    }

    @Test
    public void test1(){
        Consumer<String> cons = (x) -> System.out.println(x);
        PrintStream ps = System.out;
        Consumer<String> con = (str) -> ps.println(str);
        con.accept("Hello World!");

        System.out.println("--------------------------------");

        Consumer<String> con2 = ps::println;
        con2.accept("Hello Java8!");

        Consumer<String> con3 = System.out::println;
    }
}

 

猜你喜欢

转载自www.cnblogs.com/weilz/p/11334577.html