Java8 a note

1, changes in the interface of

Java8 changes to the interface:
① increased the default methods and static methods, both of which can have a method body.
②default method belongs example, static methods belong to the class (interface).
③ static method inside the interface will not be inherited. Static variables are inherited.

2, Lambda Expressions

Functional Interface: The interface is only an abstract method which time is a function interface, defined may be used to force annotation interface has only one abstract method.
Note: From the beginning of the introduction of Java5 comment. Bytecode files described using some notes.
@FunctionalInterface role annotation is used to tell the compiler at compile time the interface has only one abstract method.

3, Why Lambda expressions

  Lambda is an anonymous function, Lambda expressions can be understood as a piece of code that can be passed (the pass codes as image data)

// Create Entity Class 
public  class the Employee {
     Private String name;
     Private  int Age;
     Private  Double the salary; 

    // no argument constructor 
    public the Employee () { 
    } 

    // full argument constructor 
    public the Employee (String name, int Age, Double the salary ) {
         the this .name = name;
         the this .age = Age;
         the this a .salary = the 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 expression 
     * * / 
    @Test 
    public  void test2 () { 
        Comparator <Integer> COM = (X, Y) -> Integer.compare (X, Y); 
        TreeSet <Integer> = TS new new TreeSet <> (COM) ; 
    } 

    List <the employee> = the employees Arrays.asList (
             new new the employee ( "John Doe", 18,6666.66 ),
             new new the employee ( "Rees" 23,9999.99 ) 
    ); 

    / ** 
     * requirements: get the current employees older than 20 employee information 
     * * / 
    @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 basic grammar

Lambda expressions introduces a new syntax elements and operators in the Java language. This operator is "->", the operator is called Lambda operator or operators cutting head. It Lambda divided into two parts:
the left: Lambda expression specifies all the parameters required
right: Lambda specified, i.e. Lambda expressions function to be performed.
① a syntax: no arguments and returns no value, Lambda body simply a statement

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

When ②Lambda only one parameter, the parameter may be omitted parentheses

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

③Lambda requires two arguments and return values

BinaryOperator <Long> BO = (X, Y) -> { 
    System.out.println ( "function implemented interface methods!" );
     Return X + Y; 
};

④ When the body Lambda only one statement, return with braces may be omitted

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

⑤ The data type can be omitted, as inferred by the compiler, called "type inference"

BinaryOperator <Long> BO = (X Long, Long Y) -> { 
    System.out.println ( "function implemented interface methods!" );
     Return X + Y; 
};

5, the function interface

Lambda expressions need to support "function interface" of;

Example: ① interface function with two generic declaration, the generic type <T, R>   T is a parameter, R is the return value 
② abstract methods declared in the interface corresponding to 
③ in TestLambda class declaration method, using as an interface parameter calculating two long type parameters and 
④ two long type parameters recalculation product 

// declare interfaces 
public  interface MyFunction2 <T, R & lt> {
     public R & lt the getValue (T T1, T T2); 
} 

// Create a class TestLambda 
public  class TestLambda { 
    @Test 
    public  void Test3 () { 
        OP ( 100L, 200L, (X, Y) -> X + Y); 
        OP ( 100L, 200L, (X, Y) -> X * Y); 
     } 

    / ** 
     * requirements: processing data for two Long type 
     * / 
     public  void op(Long n1, Long n2, MyFunction2<Long, Long> mf){
         System.out.println(mf.getValue(n1, n2));
      }
}

Functional Interface: abstract interface only one interface method, called a function interface. You can use annotations @FunctionalInterface modification, you can check whether the function interface
① custom function interface

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

② use of the generic interface functions

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

// passed as a parameter Lambda expressions 
public String toUpperString (the MyFunc <String> MF, String STR) {
     return mf.getValue (STR); 
} 

/ / passed as parameters Lambda expressions: 
String = newStr toUpperString ( 
    (STR) -> str.toUpperCase (), "abcdef" ); 
System.out.println (newStr);    

Lambda expressions passed as a parameter: To Lambda expressions passed as a parameter, the parameter type received Lambda expressions must be compatible with the type of Lambda expression of functional interface.

6, Java8 built four core interface functions

public  class TestLambda3 { 

    // the Predicate <T> Interface assertion: 
    @Test
     public  void Test4 () { 
        List <String> Arrays.asList List = ( "the Hello", "the Lambda", "WWW", "OK" ); 
        List <String> strlist = filterStr (List, (S) -> s.length ()>. 3 ); 

        for (String STR: strlist) { 
            System.out.println (STR); 
        } 
    } 

    // requirements: satisfy the condition string into the set of 
    public List <string> filterStr (List <string> List, the Predicate <string> pre) { 
        List <string>strList = new ArrayList<>();

        for(STR String: List) {
             IF (pre.test (STR)) { 
                strList.add (STR); 
            } 
        } 

        return strlist; 
    } 

    // Function <T, R & lt> Interface Function: 
    @Test
     public  void Test3 () { 
        SUBSTR string = strHandler ( "Beijing welcomes you!", (str) -> str.substring (2, 5 )); 
        System.out.println (SUBSTR); 
    } 

    // needs: for processing string 
    public string strHandler ( STR String, Function <String, String> Fun) {
         return fun.apply (STR); 
    } 

    // Supplier <T> supplied Interface: 
    @Test
    public  void test2 () { 
        List <Integer> = getNumList numlist (10, () -> ( int ) (Math.random () * 100 )); 

        for (Integer NUM: numlist) { 
            System.out.println (NUM) ; 
        } 
    } 

    // requirements: generating a specified integer number, and placed in the collection 
    public List <integer> getNumList ( int NUM, Supplier <integer> SUP) { 
        List <integer> = List new new the ArrayList <> (); 

        for ( int I = 0; I <NUM; I ++ ) { 
            Integer n- = sup.get (); 
            List.add (n-);
        } 

        Return List; 
    } 

    // Consumer <T> Consumer Interface: 
    @Test
     public  void test1 () { 
        Happy ( 10000, (m) -> System.out.println ( "go shopping, each consumer:" + m + "yuan" )); 
    } 

    public  void Happy ( Double Money, Consumer <Double> CON) { 
        con.accept (Money); 
    } 
}

7, reference method and reference constructor

⑴, method references
as to be transmitted to the operator Lambda body has implemented method, the method may be used references!
( Implementation of the abstract method parameter list, the parameter list must reference methods and methods consistent! )

方法引用所引用的方法的参数列表与返回值类型,
需要与函数式接口中抽象方法的参数列表和返回值类型保持一致
//类名 :: 静态方法名
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;
    }
}

 

 

Guess you like

Origin www.cnblogs.com/weilz/p/11334577.html