“This is the third day of my participation in the First Challenge 2022. For details: First Challenge 2022”

preface

Hello everyone, MY name is Kano, a full stack full stick engineer!

Through the previous two chapters “Lambda must know and must know” and “Lambda built-in functional interface”, WE believe that we have a deep understanding of Lambada. Lambda can indeed simplify our code, but we may encounter such a problem in the process of using it. How should Lambda be used for existing methods? In this chapter we continue to explore another feature method reference in Java8.

Method references

Method references refer to the repeated use of existing method definitions, in this case creating Lambda expressions from existing methods to make code more readable. If in doubt, don’t panic, keep reading.

How to build it?

  • Grammar:[the name of the class | object name] : : method;
  • Construction forms: constructor method references, static method references, instance method references, object method references. As shown in the following table:
Reference form grammar Equivalent Lambda note
Constructor reference The name of the class: : new (args) -> New class name (args)
Static method reference Class name :: Method name (args) -> Class name. The method name (args)
Instance method reference Class name :: Method name (instance,args) -> instance. Method name (args) Instance is the instance of the argument passed to lambda (the first argument is the instance, followed by the method arguments to the calling method)
Object method reference Object :: method name (args) -> obj. method name (args) Obj is lambda external object (not passed in)

Instance method references and object method references may seem a bit confusing, but remember that we will use examples to understand these four forms better.

The sample

Constructor reference

The constructor argument list is replaced if it matches the functional interface arguments

  • No arguments structure
/ / Lambda form
Supplier<Apple> apple = () -> new Apple();
System.out.println(apple.get()); //com.uucoding.java.entity.Apple@305fd85d
// Construct method reference form
Supplier<Apple> appleNew = Apple::new;
System.out.println(appleNew.get()); //com.uucoding.java.entity.Apple@11438d26
Copy the code
  • Parameter construction (1 parameter)
/ / Lambda form
Function<String, Person> person = (name) -> new Person(name);
System.out.println(person.apply("Kano")); //
// Construct method reference form
Function<String, Person> personNew = Person::new; // Person(name= carno)
System.out.println(personNew.apply("Cano New")); // Person(name= carno New)
Copy the code

If there are two parameters, you can use BiFunction. If there are more parameters, you need to define the new function interface by yourself.

Static method reference

Static method input parameters and return values consistent with functional interface can be replaced!

public void testStatic(a){
    / / Lambda form
    Function<String, Integer> str2Int = (str) -> Integer.valueOf(str);
    System.out.println(str2Int.apply("100"));
    Static method references
    Function<String, Integer> str2IntNew = Integer::valueOf;
    System.out.println(str2IntNew.apply("100"));
}
Copy the code

Instance method reference

The first parameter of the function interface is the instance type, and the remaining parameters and return value types correspond to the instance method one by one, which can be replaced by instance method references.

public void testInstance(a){
	/ / Lambda form
	BiPredicate<String, String> startsWith = (str, startWithStr) -> str.startsWith(startWithStr);
	System.out.println(startsWith.test("Kano"."Card")); // true
	// Instance method
	BiPredicate<String, String> startsWithNew = String::startsWith;
	System.out.println(startsWithNew.test("Kano"."Card"));// true
}
Copy the code

Object method reference

The object must be created before the lambda uses it, and then the corresponding method is called from within the lambda. The method parameters and return values must correspond to the function interface

public void testObject(a){
    / / Lambda form
    List<Person> container = new ArrayList<>();
    Function<Person, Boolean> addFunction = person -> container.add(person);
    addFunction.apply(new Person("Kano"));
    System.out.println(container); // [Person(name= carno)]
    // Object method references
    List<Person> containerNew = new ArrayList<>();
    Function<Person, Boolean> addFunctionNew = containerNew::add;
    addFunctionNew.apply(new Person("Cano New"));
    System.out.println(containerNew); // [Person(name= carno New)]
}
Copy the code

Through the above cases, I believe that we should be familiar with the various forms of method reference! Go and try it yourself!

The source code

  • 👉 source can be accessed here

conclusion

  • This chapter mainly explains and writes cases for Lambda method references.
  • The main purpose of method references is to let us implement and pass them using existing methods;
  • The four types of method references are constructor method references, static method references, instance method references, and object method references.
  • If instance method references and object method reference suggestions seem contradictory, you can use examples to distinguish the specific differences between them.

Related articles

  • Lambda must know, must know
  • Lambda built-in functional interface

The last

  • Thank you for your patience to see the end, if you feel this article is helpful, please give aPraise 👍orFocus on ➕;
  • Due to my limited technology, the article and code may be wrong, I hope you comment pointed out, very grateful 🙏;
  • At the same time, I also welcome you to discuss learning front-end, Java knowledge, volume and progress together.