I saw a code in java 8 to iterate a collection.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.forEach(System.out::println);
What is the functionality of System.out::println
? And how the above code can iterate through the List.
And what is the use of the operator ::
, Where else we can use this operator ?
:: is a new operator included in Java 8 that is used to refer to a method of an existing class. You can refer to static methods and non-static methods of a class. The only prerequisite for referring to a method is that the method exists in a functional interface, which must be compatible with the method reference.
System. out is a reference to an object, It represents the standard output stream, and you can find its type from the link on the left. It has a method called println(), which is overloaded so it can accept absolutely anything as an argument. If you put it after the :: member access operator, it becomes an expression.
The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions.
out: This is an instance of PrintStream type, which is a public and static member field of the System class. println(): As all instances of PrintStream class have a public method println(), hence we can invoke the same on out as well.
It's called a "method reference" and it's a syntactic sugar for expressions like this:
numbers.forEach(x -> System.out.println(x));
Here, you don't actually need the name x
in order to invoke println
for each of the elements. That's where the method reference is helpful - the ::
operator denotes you will be invoking the println
method with a parameter, which name you don't specify explicitly:
numbers.forEach(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With