Sunday, May 12, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...