Lambda表達式入門足以

java-lambda-expressions-tutorial.jpg

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

一、演化過程

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<T> 斷言型接口

@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<T> 供給型接口

@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<T> 消費型接口

@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>消費型接口 T void 對類型爲T的對象應用操作,包含方法:
void accept(T t)
Supplier<T>供給型接口 T 返回類型爲T的對象,包含方法:T get();
Function<T, R>函數型接口 T R 對類型爲T的對象應用操作。
結果R類型的對象。方法:R apply(T t);
Predicate<T>斷定型接口 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類型的結果。
包含方法爲T apply(Tt);
BinaryOperator<T> T,T T 對類型爲T的對象進行二元運算,並返回T類型的結果。
包含方法爲T apply(Tt1,Tt2);
BiConsumer<T,U> T,U void 對類型爲T,U參數應用操作。
包含方法爲void accept(T t,U u)
ToIntFunction<T>
ToLongFunction<T>
ToDoubleFunction<T>
T int
long
double
分別計算int、long、double、值的函數
IntFunction<R>
LongFunction<R>
DoubleFunction<R>
int
long
double
R 參數分別爲int、long、double類型的函數

四、方法引用

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

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

  • 對象::實例方法
  • 類::靜態方法
  • 類::實例方法

注意:

  • ① <strong style='color:red;'> 方法引用所引用的方法的參數列表與返回值類型,需要與函數式接口中抽象方法的參數列表和返回值類型保持一致!</strong>
    
  • ② 若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);
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章