Posts

Showing posts from November, 2023

Method Reference in Java Streams

In Java Streams, a method reference is a shorthand notation for a lambda expression representing a specific method. It provides a more concise way to express certain types of lambda expressions. Method references are especially useful when you want to use an existing method as a lambda expression, avoiding unnecessary boilerplate code. There are four types of method references: 1) Reference to Static Method // Lambda expression nameList . stream (). forEach ( s -> System . out . println ( s )); // Method reference nameList . stream (). forEach ( System . out :: println ); 2) Reference to an Instance Method of a particular object: // Lambda expression nameList . stream (). forEach ( s -> members . validate ( s )); // Method reference nameList . stream (). forEach ( members :: validate ); 3) Reference to an Instance Method of an Arbitrary Object of a Particular Type: List < String > countryName = Arrays . asList ( "India" , "America" , "Russia...