Taking you through Functional Interface Programming:: What is it?

What is the meaning of "::" in Java?

Do you often see the following code


List list = Arrays.asList("a","b","c");

list.stream().forEach(System.out::println);

What is the syntax of this "::"?

In JAVA 8, you can use the "::" keyword to access the class's constructor, object method, and static method. Generally, there are several usages as follows.

  • Access static method//Use method: class name:: static method name , such as Integer::parseInt
  • Access object method//Usage method: instance object:: instance method , such as String::substring
  • Access constructor//Usage method: class name::new , such as User::new

Here are a few examples:

List list = Arrays.asList("1","2","3");

List collect = list.stream().map(Integer::parseInt).collect(Collectors.toList());

List collect = list.stream().map(String::toUpperCase).collect(Collectors.toList());

Seeing this, are you more curious, what does this method String::toUpperCase represent?

Let's take a look at the String::toUpperCase method separately

Function function = String::toUpperCase;

String hello = function.Apply("hello");

System.out.println(hello); //HELLO

It turns out that what String::toUpperCase returns is a functional interface (a functional interface can be implicitly converted into a lambda expression). Here we understand that the function.apply method is finally called.

Guess you like

Origin blog.csdn.net/Ghoul___/article/details/126303226