1. 程式人生 > >java8之方法引用

java8之方法引用

 XML Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.lyzx.day02;

import org.junit.Test;


public class T5{
    
    
    /**
     * 方法引用
     * 當要傳遞給Lambda體的操作,已經有實現的方法了,可以使用方法引用!
     * (實現抽象方法的引數列表,必須與方法引用方法的引數列表保持一致!)
     * 方法引用:使用操作符 "::"
 將方法名和物件或類的名字分隔開來。
     * 如下三種主要使用情況:
     * 物件::例項方法
     * 類::靜態方法
     * 類::例項方法
     */
    @Test
    public void test1(){
        //加入Calculate的calc方法是求兩個數中大的,而Math的max方法正好是這個功能
        //所以可以使用Math::max 即類::靜態方法名
        Calculate c = Math::max;
        int max = c.calc(9,900);
        System.out.println(max);
    }
}

@FunctionalInterface
interface Calculate{
    public int calc(int a,int b);
}

@FunctionalInterface
interface Str{
    public String toUpper(String str);
}