Difference between System.out::print and System.out.print


Link: https://www.zhihu.com/question/45218076/answer/98632631
Source: Zhihu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

System.out::print : is a method reference

Method references are useful when you want to pass a method as a "function pointer" to another method.

For example, I have an ArrayList that I want to print out for each element, one line per element.
So before Java 8 it would have been written like this:
  for (ElementType e : list) {
    System.out.println(e);
  }
Since Java 8, using ArrayList's new API plus lambda expressions, we can write:
  list.forEach(e -> System.out.println(e));
The content of the lambda expression here is actually just passing the parameters to the println() method without doing anything else, so it can be further abbreviated as:
  list.forEach(System.out::println);

That's all.

Highlights:
  • System.out is a reference to a PrintStream instance; System.out::println is a reference to an instance method
    • The reference specifies both a reference to the instance (System.out) and a reference to the method (PrintStream::println)
  • System.out::println is not the equivalent of System.out.println; the former is a method reference expression, while the latter cannot stand alone as an expression, but must be followed by a parenthesized argument list to form a method invocation expression Mode.
  • System.out::println can be seen as a shorthand for the lambda expression e -> System.out.println(e).

Guess you like

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