:: (double colon) operator in Java 8
In Java 8, the ::
(double colon) operator is used to refer to a method or a constructor. It can be used in a method reference, which is a shorthand for a lambda expression that calls a specific method.
Here is an example of using the ::
operator to create a method reference:
List<String> strings = Arrays.asList("a", "b", "c");
strings.forEach(System.out::println);
In this example, the System.out::println
method reference is used to print the elements of the strings
list. It is equivalent to the following lambda expression:
strings.forEach(s -> System.out.println(s));
The ::
operator can also be used to refer to a constructor, as in the following example:
Function<String, Integer> parseInt = Integer::new;
int number = parseInt.apply("123");
In this example, the Integer::new
method reference is used to create an Integer
object from a string. It is equivalent to the following lambda expression:
Function<String, Integer> parseInt = s -> new Integer(s);
int number = parseInt.apply("123");
I hope this helps. Let me know if you have any questions.