Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use double colons in java8

Shulou Source: shulou.com Published: 2022-06-02 12:56:58 09月26日 Update

This article mainly explains "how to use double colons in java8". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use double colons in java8.

The code is actually very simple:

The previous code generally looked like this:

Public class AcceptMethod {public static void printValur (String str) {System.out.println ("print value:" + str);} public static void main (String [] args) {List al = Arrays.asList ("a", "b", "c", "d"); for (String a: al) {AcceptMethod.printValur (a);} / / the for each cycle below and the cycle above are equivalent al.forEach (x-> {AcceptMethod.printValur (x);});}}

Now the JDK double colon is:

Public class MyTest {public static void printValur (String str) {System.out.println ("print value:" + str);} public static void main (String [] args) {List al = Arrays.asList ("a", "b", "c", "d"); al.forEach (AcceptMethod::printValur); / / the following method and the above equivalent Consumer methodParam = AcceptMethod::printValur; / / method parameter al.forEach (x-> methodParam.accept (x)); / / method execution accept}}

The execution results of all the above methods are as follows:

Print value: aprint value: bprint value: cprint value: d

In JDK8, the forEach method is implemented by default in interface Iterable 8, and the accept method in the interface Consumer added in JDK8 is called to execute the passed method parameters.

The JDK source code is as follows:

/ * * Performs the given action for each element of the {@ code Iterable} * until all elements have been processed or the action throws an * exception. Unless otherwise specified by the implementing class, * actions are performed in the order of iteration (if an iteration order * is specified). Exceptions thrown by the action are relayed to the * caller. * * @ implSpec *

The default implementation behaves as if: * {@ code * for (T: this) * action.accept (t); *} * * @ param action The action to be performed for each element * @ throws NullPointerException if the specified action is null * @ since 1.8 * / default void forEach (Consumer

Tags: Methods interfaces colons facets code content parameters equivalence learning loops practicality deeper no interest functions suffixes practicality practicality that is simple operation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Shulou Tech Info MariaDB Redmi Microsoft