【Way to java】Java8 新特性 1

Java8簡介

  • 速度更快
  • 代碼更少(新增了新的語法Lambda表達式)
  • 強大的Stream API
  • 便於並行
  • 最大化減少空指針異常Optional

其中最爲核心的是Lambda表達式Stream API

Lambda表達式

簡介

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

案例

場景:從員工集合中篩選某些條件的員工

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)
);

方案一:for循環篩選

//需求:獲取公司中年齡小於 35 的員工信息
public List<Employee> filterEmployeeAge(List<Employee> emps){
	List<Employee> list = new ArrayList<>();
	for (Employee emp : emps) {
		if(emp.getAge() <= 35){
			list.add(emp);
		}
	}
	return list;
}

方案二:通過策略設計模式泛型調用,後續增加規則類

@FunctionalInterface
public interface MyPredicate<T> {
	public boolean test(T t);
}

public class FilterEmployeeForAge implements MyPredicate<Employee>{
	@Override
	public boolean test(Employee t) {
		return t.getAge() <= 35;
	}
}
public List<Employee> filterEmployee(List<Employee> emps, MyPredicate<Employee> mp){
	List<Employee> list = new ArrayList<>();
	for (Employee employee : emps) {
		if(mp.test(employee)){
			list.add(employee);
		}
	}
	return list;
}

方案三:通過匿名內部類

@Test
public void test5(){
	List<Employee> list = filterEmployee(emps, new MyPredicate<Employee>() {
		@Override
		public boolean test(Employee t) {
			return t.getId() <= 103;
		}
	});
	for (Employee employee : list) {
		System.out.println(employee);
	}
}

方案四:通過lambda表達式

@Test
public void test6(){
	List<Employee> list = filterEmployee(emps, (e) -> e.getAge() <= 35);
	list.forEach(System.out::println);
	
	System.out.println("------------------------------------------");
	
	List<Employee> list2 = filterEmployee(emps, (e) -> e.getSalary() >= 5000);
	list2.forEach(System.out::println);
}

方案五:Stream API

@Test
public void test7(){
	emps.stream()
		.filter((e) -> e.getAge() <= 35)
		.forEach(System.out::println);
	System.out.println("---------------------------------");
	emps.stream()
		.map(Employee::getName)
		.limit(3)
		.sorted()
		.forEach(System.out::println);
}

語法

Lambda 表達式在Java 語言中引入了一個新的語法元素和操作符。這個操作符爲 “->” , 該操作符被稱爲 Lambda 操作符或剪頭操作符。它將 Lambda 分爲兩個部分:
左側:指定了 Lambda 表達式需要的所有參數
右側:指定了 Lambda 體,即 Lambda 表達式要執行的功能

無參 無返回值

@Test
public void test1(){
	int num = 0;//jdk1.7前,必須是final,1.8後可以不用寫但是不能num++
	Runnable r = new Runnable() {
		@Override
		public void run() {
			System.out.println("Hello World!" + num);
		}
	};
	r.run();
	System.out.println("-------------------------------");
	Runnable r1 = () -> System.out.println("Hello Lambda!");
	r1.run();
}

一個參數 無返回值

@Test
public void test2(){
	Consumer<String> con = x -> System.out.println(x);
	con.accept("Hello world!");
}

兩個以上的參數,有返回值,有多條語句

Comparator<Integer> com = (x, y) -> {
	System.out.println("函數式接口");
	return Integer.compare(x, y);
};

兩個以上的參數,有返回值,一條語句

// return和大括號可以省略
// 
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);

總結

  1. Lambda 表達式的參數列表的數據類型可以省略不寫,因爲JVM編譯器通過上下文推斷出,數據類型,即“類型推斷” ,也可以聲明參數類型例如 (Integer x, Integer y) -> Integer.compare(x, y);
  2. 接口中只有一個抽象方法的接口,稱爲函數式接口。 可以使用註解 @FunctionalInterface 修飾可以檢查是否是函數式接口

函數式接口

簡介

  1. 只包含一個抽象方法的接口,稱爲函數式接口。
  2. 可以通過 Lambda 表達式來創建該接口的對象。(若 Lambda
    表達式拋出一個受檢異常,那麼該異常需要在目標接口的抽象方
    法上進行聲明)
  3. 我們可以在任意函數式接口上使用 @FunctionalInterface 註解,
    這樣做可以檢查它是否是一個函數式接口,同時 javadoc 也會包
    含一條聲明,說明這個接口是一個函數式接口

四大內置核心函數式接口

消費型接口

Consumer<T> void accept(T t);

@Test
public void test1(){
	happy(100, (m) -> System.out.println("此次消費" + m + "元"));
} 
public void happy(double money, Consumer<Double> con){
	con.accept(money);
}

供給型接口

Supplier<T> T get();

@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;
}

函數型接口

Function<T, R> R apply(T t);

@Test
public void test3(){
	String newStr = strHandler("\t\t\t Helloworld   ", (str) -> str.trim());
	System.out.println(newStr);
	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);
}

斷言型接口

Predicate<T> boolean test(T t);

@Test 
public void test4(){
	List<String> list = Arrays.asList("Hello", "atguigu", "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;
}

其他

在這裏插入圖片描述

方法引用

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

方法引用所引用的方法的參數列表與返回值類型,需要與函數式接口中抽象方法的參數列表和返回值類型保持一致

若Lambda 的參數列表的第一個參數,是實例方法的調用者,第二個參數(或無參)是實例方法的參數時,格式: ClassName::MethodName

  • 對象::實例方法
Consumer<String> con1 = (x) -> System.out.println(x);
con1.accept("helloworld");
Consumer<String> con2 = System.out::println;
con2.accept("helloworld");
  • 類::靜態方法
@Test
public void test4(){
	Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
	System.out.println("-------------------------------------");
	Comparator<Integer> com2 = Integer::compare;
}
  • 類::實例方法
@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 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 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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章