1. 程式人生 > 其它 >攜程四面:說說Lambda表示式的演化過程!

攜程四面:說說Lambda表示式的演化過程!

前言

能夠使用Lambda的依據是必須有相應的函式介面(函式介面,是指內部只有一個抽象方法的介面)。 這一點跟Java是強型別語言吻合,也就是說你並不能在程式碼的任何地方任性的寫Lambda表示式。實際上Lambda的型別就是對應函式介面的型別。Lambda表示式另一個依據是型別推斷機制(重點),在上下文資訊足夠的情況下,編譯器可以推斷出引數表的型別,而不需要顯式指名

讀者福利:Java核心學習筆記+2021最新大廠面試真題共享!

一、演化過程

A.基礎類的準備

package com.os.model;
import java.util.Objects;
public class Employee {
	private int id;
	private String name;
	private int age;
	private double salary;
	//省略生成的getteer和setter方法,構造方法、toString方法、hashCode、equals方法
}
複製程式碼

B.篩選資料

我們根據不同的篩選條件需要設定不同的方法,增加了很多的程式碼量。

package com.os.test;

import com.os.model.Employee;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Demo01 {
	private static List<Employee> emps = Arrays.asList(
			new Employee(101, "悟空", 18, 9999.99),
			new Employee(102, "八戒", 59, 6666.66),
			new Employee(103, "唐僧", 28, 3333.33),
			new Employee(104, "沙僧", 8, 7777.77),
			new Employee(105, "白龍馬", 38, 5555.55)
	);
	public static void main(String[] args) {
		System.out.println("===>1.篩選年齡");
		List<Employee> list = filterEmployeeAge(emps);
		for (Employee employee : list) {
			System.out.println(employee);
		}
		System.out.println("===>2.篩選工資");
		list = filterEmployeeSalary(emps);
		for (Employee employee : list) {
			System.out.println(employee);
		}
	}
	/**
	 * 需求:獲取公司中年齡小於 35 的員工資訊
	 * @param employeeList
	 * @return
	 */
	public static List<Employee> filterEmployeeAge(List<Employee> employeeList){
		List<Employee> list = new ArrayList<>();

		for (Employee emp : employeeList) {
			if(emp.getAge() <= 35){
				list.add(emp);
			}
		}
		return list;
	}

	/**
	 * 需求:獲取公司中工資大於 5000 的員工資訊
	 * @param employeeList
	 * @return
	 */
	public static List<Employee> filterEmployeeSalary(List<Employee> employeeList){
		List<Employee> list = new ArrayList<>();

		for (Employee emp : employeeList) {
			if(emp.getSalary() >= 5000){
				list.add(emp);
			}
		}

		return list;
	}
}
複製程式碼

C.程式碼進化:策略設計模式

(1)定義篩選條件的泛型介面

package com.os.service;
/**
 * 針對於資料的篩選條件的介面
 */
public interface ObjectDataPredicate<T> {
	boolean test(T t);
}
複製程式碼

(2)實現類去實現不同的篩選方式

按照年齡進行篩選實現類

package com.os.service;

import com.os.model.Employee;

public class FilterEmployeeForAge implements ObjectDataPredicate<Employee> {
	@Override
	public boolean test(Employee employee) {
		return employee.getAge() <= 35;
	}
}
複製程式碼

按照工資進行篩選實現類

package com.os.service;

import com.os.model.Employee;

public class FilterEmployeeForSalary implements ObjectDataPredicate<Employee> {
	@Override
	public boolean test(Employee employee) {
		return employee.getSalary() >= 5000;
	}
}
複製程式碼

(3)策略模式的實現程式碼

public static List<Employee> filterEmployee(List<Employee> emps, ObjectDataPredicate<Employee> objectDataPredicate){
    List<Employee> list = new ArrayList<>();
    for (Employee employee : emps) {
        if(objectDataPredicate.test(employee)){
            list.add(employee);
        }
    }
    return list;
}
複製程式碼

完整程式碼如下

package com.os.test;

import com.os.model.Employee;
import com.os.service.FilterEmployeeForAge;
import com.os.service.FilterEmployeeForSalary;
import com.os.service.ObjectDataPredicate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Demo02 {
    private static List<Employee> emps = Arrays.asList(
        new Employee(101, "悟空", 18, 9999.99),
        new Employee(102, "八戒", 59, 6666.66),
        new Employee(103, "唐僧", 28, 3333.33),
        new Employee(104, "沙僧", 8, 7777.77),
        new Employee(105, "白龍馬", 38, 5555.55)
    );
    public static void main(String[] args) {
        List<Employee> list = filterEmployee(emps, new FilterEmployeeForAge());//介面回撥
        for (Employee employee : list) {
            System.out.println(employee);
        }

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

        List<Employee> list2 = filterEmployee(emps, new FilterEmployeeForSalary());//介面回撥
        for (Employee employee : list2) {
            System.out.println(employee);
        }
    }

    public static List<Employee> filterEmployee(List<Employee> emps, ObjectDataPredicate<Employee> objectDataPredicate){
        List<Employee> list = new ArrayList<>();
        for (Employee employee : emps) {
            if(objectDataPredicate.test(employee)){
                list.add(employee);
            }
        }
        return list;
    }
}
複製程式碼

這種程式碼的實現類太多了

D.程式碼進化:匿名內部類

package com.os.test;

import com.os.model.Employee;
import com.os.service.FilterEmployeeForAge;
import com.os.service.FilterEmployeeForSalary;
import com.os.service.ObjectDataPredicate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Demo03 {
    private static List<Employee> emps = Arrays.asList(
        new Employee(101, "悟空", 18, 9999.99),
        new Employee(102, "八戒", 59, 6666.66),
        new Employee(103, "唐僧", 28, 3333.33),
        new Employee(104, "沙僧", 8, 7777.77),
        new Employee(105, "白龍馬", 38, 5555.55)
    );
    public static void main(String[] args) {
        List<Employee> list = filterEmployee(emps, new ObjectDataPredicate<Employee>() {
            @Override
            public boolean test(Employee employee) {
                return employee.getId() <= 103;
            }
        });//介面回撥
        for (Employee employee : list) {
            System.out.println(employee);
        }
    }
    public static List<Employee> filterEmployee(List<Employee> emps, ObjectDataPredicate<Employee> objectDataPredicate){
        List<Employee> list = new ArrayList<>();
        for (Employee employee : emps) {
            if(objectDataPredicate.test(employee)){
                list.add(employee);
            }
        }
        return list;
    }
}
複製程式碼

通過內部類,我們能發現整個程式碼中核心的部分就是一句話employee.getId() <= 103

E.程式碼進化:Lambda 表示式

package com.os.test;

import com.os.model.Employee;
import com.os.service.ObjectDataPredicate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Demo04 {
	private static List<Employee> emps = Arrays.asList(
			new Employee(101, "悟空", 18, 9999.99),
			new Employee(102, "八戒", 59, 6666.66),
			new Employee(103, "唐僧", 28, 3333.33),
			new Employee(104, "沙僧", 8, 7777.77),
			new Employee(105, "白龍馬", 38, 5555.55)
	);
	public static void main(String[] args) {
        /*
         List<Employee> list = filterEmployee(emps, new ObjectDataPredicate<Employee>() {
            @Override
            public boolean test(Employee employee) {
                return employee.getId() <= 103;
            }
        });//介面回撥
        */
		List<Employee> list = filterEmployee(emps, (e) -> e.getAge() <= 35);
		for (Employee employee : list) {
			System.out.println(employee);
		}

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

		List<Employee> list2 = filterEmployee(emps, (e) -> e.getSalary() >= 5000);
		for (Employee employee : list2) {
			System.out.println(employee);
		}
	}

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

複製程式碼

Lambda 是一個匿名函式,我們可以把Lambda 表示式理解為是一段可以傳遞的程式碼(將程式碼像資料一樣進行傳遞)。可以寫出更簡潔、更靈活的程式碼。作為一種更緊湊的程式碼風格,使Java的語言表達能力得到了提升。

二、Lambda基礎語法

Lambda 表示式在Java 語言中引入了一個新的語法元素和操作符。這個操作符為->,該操作符被稱為Lambda 操作符或剪頭操作符。它將Lambda 分為兩個部分:

  • 左側:指定了Lambda 表示式需要的所有引數(對應介面中形參)
  • 右側:指定了Lambda 體,即Lambda 表示式要執行的功能。(方法體,可以推斷返回值型別)

A.格式1:無引數,無返回值

package com.os.print.service;
@FunctionalInterface//定義介面函式
public interface Printer01 {
	void print();
}
複製程式碼
package com.os.print.service;

public class Demo01 {
	public static void main(String[] args) {
		//之前我們可以使用你們實現類
		Printer01 out = new Printer01() {
			@Override
			public void print() {
				System.out.println("匿名實現類");
				System.out.println("====>"+Math.random());
			}
		};
		out.print();
		//使用Lambda表示式
		out = ()-> System.out.println("方法體只有一行,可以省略大括號");
		out.print();

		out = ()->{
			System.out.println("方法體有很多,需要使用大括號搞定");
			System.out.println("====>"+Math.random());
		};
		out.print();
	}
}
複製程式碼

B.格式2:有一個引數,無返回值

package com.os.print.service;
@FunctionalInterface//定義介面函式
public interface Printer02<T> {
	void print(T t);
}
複製程式碼
public class Demo02 {
	public static void main(String[] args) {
		//通過泛型推斷引數e的型別
		Printer02<Employee> out01 = (e)-> System.out.println(e);
		out01.print(new Employee(999,"悟空",19,25000));

		Printer02<Integer> out2 = (e)-> System.out.println(e);
		out2.print(999);

		Printer02<String> out3 = (e)-> System.out.println(e);
		out3.print("西遊記");
	}
}
複製程式碼

C.格式3:若只有一個引數,小括號可以省略不寫

package com.os.print.service;

import com.os.model.Employee;

public class Demo02 {
	public static void main(String[] args) {
		//通過泛型推斷引數e的型別
		Printer02<Employee> out01 = e-> System.out.println(e);
		out01.print(new Employee(999,"悟空",19,25000));

		Printer02<Integer> out2 = e-> System.out.println(e);
		out2.print(999);

		Printer02<String> out3 = e-> System.out.println(e);
		out3.print("西遊記");
	}
}
複製程式碼

D.格式4:有兩個以上的引數,有返回值,並且 Lambda 體中有多條語句

使用系統有的函式介面測試如下:

package com.os.print.service;

import com.os.model.Employee;
import java.util.Comparator;

public class Demo03 {
	public static void main(String[] args) {
		/*
		public interface Comparator<T> {
		}
		* */
		Comparator<Integer> comparator = (x,y)->{
			System.out.println("介面函式方法");
			return Integer.compare(x,y);
		};
	}
}
複製程式碼

自定義函式介面方法:

package com.os.print.service;
@FunctionalInterface//定義介面函式
public interface Printer03<T> {
	T print(T t1,T t2);
}
複製程式碼
package com.os.print.service;

import com.os.model.Employee;

import java.util.Comparator;

public class Demo03 {
	public static void main(String[] args) {
		Printer03<String> out01 = (s1,s2)->{
			String str = s1.concat(s2);
			return str.toUpperCase();
		};
		System.out.println(out01.print("abc","efg"));
	}
}
複製程式碼

自定義函式介面方法兩個引數:

package com.os.print.service;
@FunctionalInterface//定義介面函式
public interface Printer04<T,R> {
	R print(T t1, R t2);
}
複製程式碼
package com.os.print.service;

import com.os.model.Employee;
public class Demo04 {
	public static void main(String[] args) {
		Printer04<String, Employee> out = (name,e)->{
			e.setName(name);
			return e;
		};
		Employee employee = out.print("西遊記",new Employee());
		System.out.println(employee);
	}
}
複製程式碼

E.格式5:若 Lambda 體中只有一條語句, return 和 大括號都可以省略不寫

package com.os.print.service;

import com.os.model.Employee;

import java.util.Comparator;

public class Demo04 {
	public static void main(String[] args) {
		Comparator<Integer> comparator = (x, y)->Integer.compare(x,y);
        
		System.out.println(comparator.compare(1,2));
		Printer04<String, Employee> out = (name,e)->e;
		Employee employee = out.print("西遊記",new Employee());
		System.out.println(employee);
	}
}
複製程式碼

F.格式5:Lambda 表示式的引數列表的資料型別可以省略不寫,因為JVM編譯器通過上下文推斷出,資料型別,即“型別推斷”

(Integer x, Integer y) -> Integer.compare(x, y);  //一般不會使用這種寫法
複製程式碼

上述Lambda 表示式中的引數型別都是由編譯器推斷得出的。Lambda 表示式中無需指定型別,程式依然可以編譯,這是因為javac根據程式的上下文,在後臺推斷出了引數的型別。Lambda 表示式的型別依賴於上下文環境,是由編譯器推斷出來的。這就是所謂的“型別推斷”

lambda語法的總結如下:

  • 上聯:左右遇一括號省
  • 下聯:左側推斷型別省
  • 橫批:能省則省

三、函式式介面

  • 只包含一個抽象方法的介面,稱為函式式介面。

  • 你可以通過Lambda 表示式來建立該介面的物件。

    • (若Lambda 表示式丟擲一個受檢異常,那麼該異常需要在目標介面的抽象方法上進行宣告)。
  • 在任意函式式介面上設定@FunctionalInterface註解,這樣做可以檢查它是否是一個函式式介面,同時javadoc也會包含一條宣告,說明這個介面是一個函式式介面。

上述的示例中,我們已經定義過函式式介面,但是我們不可能每次都要自己定義函式式介面,太麻煩!所以,Java內建了函式式介面在java.util.function包下

A.Predicate 斷言型介面

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}    
複製程式碼
package com.os.print.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Demo05 {
	public static void main(String[] args) {
		List<String> list = Arrays.asList("Hello", "pangsir", "Lambda", "www", "ok");
		List<String> strList = filterStr(list, (s) -> s.length() > 3);
		for (String str : strList) {
			System.out.println(str);
		}
	}
	//需求:將滿足條件的字串,放入集合中
	public static 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;
	}
}
複製程式碼

B.Function<T,R> 函式型介面

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}    
複製程式碼
package com.os.print.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;

public class Demo06 {
	public static void main(String[] args) {
		String newStr = strHandler("\t\t\t 西遊記齊天大聖孫悟空   ", (str) -> str.trim());
		System.out.println(newStr);

		String subStr = strHandler("西遊記齊天大聖孫悟空", (str) -> str.substring(2, 5));
		System.out.println(subStr);
	}
	//需求:用於處理字串
	public static String strHandler(String str, Function<String, String> fun){
		return fun.apply(str);
	}
}
複製程式碼

C.Supplier 供給型介面

@FunctionalInterface
public interface Supplier<T> {
    T get();
}
複製程式碼
package com.os.print.service;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

public class Demo07 {
	public static void main(String[] args) {
		List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));

		for (Integer num : numList) {
			System.out.println(num);
		}
	}
	//需求:產生指定個數的整數,並放入集合中
	public static 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;
	}
}

複製程式碼

D.Consumer 消費型介面

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}    
複製程式碼
package com.os.print.service;
import java.util.function.Consumer;
public class Demo08 {
	public static void main(String[] args) {
		happy(10000, (m) -> System.out.println("購物消費:" + m + "元"));
	}
	public static void happy(double money, Consumer<Double> con){
		con.accept(money);
	}
}
複製程式碼

java.util.function包下有很多有用的函式式介面

函式式介面 引數型別 返回型別 用途
Consumer消費型介面 T void 對型別為T的物件應用操作,包含方法:void accept(T t)
Supplier供給型介面 T 返回型別為T的物件,包含方法:T get();
Function<T, R>函式型介面 T R 對型別為T的物件應用操作。結果R型別的物件。方法:R apply(T t);
Predicate斷定型介面 T boolean 確定型別為T的物件是否滿足某約束,boolean 值。含方法boolean test(T t);
BiFunction<T,U,R> T,U R 對型別為T,U引數應用操作,返回R型別的結果。包含方法為:R apply(T t,U u);
UnaryOperator T T 對型別為T的物件進行一元運算,並返回T型別的結果。包含方法為T apply(Tt);
BinaryOperator T,T T 對型別為T的物件進行二元運算,並返回T型別的結果。包含方法為T apply(Tt1,Tt2);
BiConsumer<T,U> T,U void 對型別為T,U引數應用操作。包含方法為void accept(T t,U u)
ToIntFunctionToLongFunctionToDoubleFunction T intlongdouble 分別計算int、long、double、值的函式
IntFunctionLongFunctionDoubleFunction intlongdouble R 引數分別為int、long、double型別的函式

四、方法引用

當要傳遞給Lambda體的操作,已經有實現的方法了,可以使用方法引用!

方法引用:使用操作符“::” 將方法名和物件或類的名字分隔開來。

  • 物件::例項方法
  • 類::靜態方法
  • 類::例項方法

注意:

  • 方法引用所引用的方法的引數列表與返回值型別,需要與函式式介面中抽象方法的引數列表和返回值型別保持一致! 複製程式碼

  • ② 若Lambda 的引數列表的第一個引數,是例項方法的呼叫者,第二個引數(或無參)是例項方法的引數時,格式: ClassName::MethodName 複製程式碼

A.物件的引用 :: 例項方法名

package com.os.print.service;

import com.os.model.Employee;
import java.util.function.Supplier;

public class Demo09 {
	public static void main(String[] args) {
		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());
	}
}
複製程式碼

B.類 :: 靜態方法名

package com.os.print.service;

import java.util.function.BiFunction;
import java.util.function.Supplier;
public class Demo10 {
	public static void main(String[] args) {
		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));
	}
}
複製程式碼

C.類 :: 例項方法名

package com.os.print.service;

import com.os.model.Employee;

import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;

public class Demo11 {
	public static void main(String[] args) {
		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.getName();
		System.out.println(fun.apply(new Employee()));

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

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

}

複製程式碼

若Lambda 的引數列表的第一個引數,是例項方法的呼叫者,第二個引數(或無參)是例項方法的引數時,格式: ClassName::MethodName

D.構造方法引用 ClassName::new

格式:ClassName::new 與函式式介面相結合,自動與函式式介面中方法相容。 可以把構造器引用賦值給定義的方法,與構造器引數列表要與介面中抽象方法的引數列表一致!

package com.os.print.service;

import com.os.model.Employee;

import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;

public class Demo12 {
	public static void main(String[] args) {

		Function<String, Employee> fun = Employee::new;
		System.out.println(fun.apply("悟空"));

		BiFunction<String, Integer, Employee> fun2 = Employee::new;
		System.out.println(fun2.apply("八戒",18));
	}

}
複製程式碼

E.陣列引用

package com.os.print.service;

import com.os.model.Employee;

import java.util.function.BiFunction;
import java.util.function.Function;

public class Demo13 {
	public static void main(String[] args) {

		Function<Integer, String[]> fun = (e) -> new String[e];
		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);
	}

}

關注公眾號:麒麟改bug 共享2021金三銀四Java面試題總結集錦!