Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of "System.out::println" in Java 8 [duplicate]

Tags:

java

java-8

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 ?

like image 721
prime Avatar asked Jun 24 '15 07:06

prime


People also ask

What is the use of :: in Java 8?

:: 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.

What is the use of System out :: Println?

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.

What does mean :: in Java?

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.

What is the type of System out :: Println?

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.


1 Answers

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); 
like image 56
Konstantin Yovkov Avatar answered Sep 24 '22 20:09

Konstantin Yovkov