Sunday 12 May 2019

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




I saw a code in java 8 to iterate a collection.



List 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 ?


Answer



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);

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...