How to use forEach and method reference in Java

Hello there,

In this article I will explain how can we make use of one of the feature of Java 8+ to print elements in the List. Java 8 onward you will see method reference feature, which is nothing but is a shorthand notation of a lambda expression to call a method.

for example

programingLanguage -> System.out.println(programingLanguage)

can be written as

System.out::println

by using this feature and forEach loop in Java we can print the each element in the list as follows (How to add Elements in List ?):

//method call to print each element in List
programingLanguages.forEach(System.out::println);

Feel free to ask questions or comment below your queries

Leave a Reply

Shopping cart

0
image/svg+xml

No products in the cart.

Continue Shopping