Java Lambda 方法的引用(更为简洁的语法糖)

方法引用的使用: 本质就是语法糖,靠记忆活用。

  1. 使用情景: Lambda体只有一行方法调用的代码,且该方法的参数列表(除一些特例)和返回类型和函数式接口的抽象方法相同。
  2. 可以理解为函数式接口的抽象方法的方法体使用的是Lambda体中调用方法的方法体(实现)。
  3. 使用格式: 类或对象::方法名
  4. 三种使用规则:
    对象 :: 非静态方法
    类 :: 静态方法
    类 :: 非静态方法 (特别注意)

代码示例:

import org.junit.jupiter.api.Test;

import static java.lang.System.out;

import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

public class LambdaTest3 {
	
	@Test
	public void test1(){
		PrintStream printStream = System.out;
		//对象 :: 非静态方法
		Consumer<String> consumer = printStream :: println;
		consumer.accept("Hello world.");
	}
	
	@Test
	public void test2() {
		Person person = new Person();
		//对象 :: 非静态方法
		Supplier<String> supplier = person :: toString;
		out.println(supplier.get());
	}
	
	@Test
	public void test3() {
		//类 :: 静态方法
		Consumer<String> consumer = Person :: shout;
		consumer.accept("How dare you!");
	}
	
	@Test
	public void test4() {
		//类 :: 静态方法
		Comparator<Integer> comparator = Integer :: compare;
		out.println(comparator.compare(1, 2));
	}
	
	@Test
	public void test5() {
		//类 :: 非静态方法(构造器)
		Supplier<Person> supplier = Person :: new;
		out.println(supplier.get());
	}
	
	@Test
	public void test6() {
		//类 :: 静态方法
		Function<Double, Long> function = Math :: round;
		out.println(function.apply(2.2));
	}
	
	@Test
	public void test7() {
		//特殊情况:只有靠记忆,一般不用。
		//int compareTo(Integer anotherInteger)
		//int compare(T o1, T o2);
		Comparator<Integer> comparator = Integer :: compareTo;
		out.println(comparator.compare(1, 0));
	}
	
	@Test 
	public void test8() {
		//类 :: 非静态方法 
		//特殊情况
		Function<Person, String> function = Person :: getName;
		out.println(function.apply(new Person()));
	}
	
	@Test 
	public void test9() {
		//类 :: 非静态方法(构造器)
		BiFunction<String, Integer, Person> function = Person :: new;
		out.println(function.apply("Michael", 25));
	}
	
	@Test
	public void test10(){
		//类 :: 非静态方法(看做构造器)
		Function<Integer, String []> function = String [] :: new;
		out.println(Arrays.toString(function.apply(10)));
	}

}

输出:

[null, null, null, null, null, null, null, null, null, null]
Hello world.
Person [name=Nobody, gender=0, age=0]
How dare you!
-1
Person [name=Nobody, gender=0, age=0]
2
1
Nobody
Person [name=Michael, gender=25, age=0]
发布了70 篇原创文章 · 获赞 4 · 访问量 3038

猜你喜欢

转载自blog.csdn.net/qq_34515959/article/details/105003123
今日推荐