Let's learn Java8 together (3) - method reference

There 一起来学Java8(一)——函数式编程is a simple functional programming example in:

import java.util.function.Consumer;

class Person {
    public static void sayHello(String name) {
        System.out.println("hello " + name);
    }
}

public class TestPerson {

	public static void main(String[] args) {
		work(Person::sayHello); // hello Jim
	}
	
	public static void work(Consumer<String> consumer) {
		consumer.accept("Jim");
	}
}

where Person::sayHellois called 方法引用, method references can be replaced with lambda expressions, the code is as follows:

public static void main(String[] args) {
	work((name) -> {
		System.out.println("hello " + name);
	}); // hello Jim
}

Method references and Lambda relationships

What is the relationship between method references and lambda expressions?

Method references can be thought of as a shortcut for lambda expressions. This shortcut is based on certain conditions and can be roughly divided into three categories:

  1. static method reference
  2. own type method reference
  3. Existing instance method reference

static method reference

The example mentioned above is a static method reference, we can also use other static methods instead

public static void main(String[] args) {
	work(String::toString);
	work(String::toLowerCase);
}

As you can see, the Lambda expression has one parameter (String name). String.toString, String.toLowerCase and Person.sayHello are also of the same parameter type. As long as the parameter signatures are consistent, they can be used instead.

own type method reference

This method can be used when the object method in the parameter is used directly in the method body of the lambda expression. For example the following example:

public static void main(String[] args) {
	// 方式1,使用Lambda表达式
	print("hello", (String s) -> s.toLowerCase());
	// 方式2,使用方法引用
	print("hello", String::toLowerCase);
}

private static void print(String argu, Consumer<String> consumer) {
	consumer.accept(argu);
}

There is a parameter in the Lambada expression. (String s)The method in the parameter object is directly used in the method body s.toLowerCase(), so it can be abbreviated as:String::toLowerCase

Here's a more complicated example:

package learn.java8.ch3;

import java.util.function.Function;

class Goods {
	private int price;

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}
}

class GoodsService {
	private Goods goods;

	public GoodsService(Goods goods) {
		super();
		this.goods = goods;
	}

	public void showPrice(Function<Goods, Integer> fun) {
		int price = fun.apply(goods);
		System.out.println("商品价格:" + price);
	}
}

public class TestPerson2 {

	public static void main(String[] args) {
		Goods goodsApple = new Goods();
		goodsApple.setPrice(100);

		GoodsService service = new GoodsService(goodsApple);
		// 方式1,使用Lambda表达式
		service.showPrice((Goods goods) -> {
			return goods.getPrice();
		});
		
		// 方式2,使用方法引用
		service.showPrice(Goods::getPrice);
	}

}

There is a Lambda expression in method 1, the parameter is Goods goods, and the getPrice of the goods object is directly called in the method body, so it can be simplified as:service.showPrice(Goods::getPrice);

Existing instance method reference

When the object method in the parameter is not used in the method body of the lambda expression, the method of other objects is used. Such as the following example

package learn.java8.ch3;

import java.util.function.Consumer;

class Dog {
	private int age;

	public Dog(int age) {
		super();
		this.age = age;
	}

	public void say(String name) {
		System.out.println("dog age is " + age + ", dog name is " + name);
	}
}

public class TestPerson4 {

	public static void main(String[] args) {
		Dog dog = new Dog(3);
		// 方式1,使用Lambda表达式
		print("Tom", (String s) -> dog.say(s));
		// 方式2,实例对象方法引用
		print("Tom", dog::say);
	}

	private static void print(String argu, Consumer<String> consumer) {
		consumer.accept(argu);
	}

}

The difference between the second and the third is whether the Lambda method body directly uses the method in the Lambda parameter.

The following summarizes the equivalence relationship between lambda expressions and method references:

  • (Dog dog) -> dog.getAge() 等价于 Dog::getAge
  • () -> XXClass.run() is equivalent to XXClass::run
  • (dog, name) -> dog.say(name) 等价于 Dog::say
  • (name) -> dog.say(name) is equivalent to dog::say

summary

This article mainly introduces method references, and demonstrates three different method references.

Regularly share technical dry goods, learn together, and progress together!

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324120856&siteId=291194637