Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 05:20:52 Viewed : 237
Method references in Java provide a shorthand syntax for creating lambda expressions that directly invoke methods or constructors. They make the code concise and improve readability. Method references are a way to refer to a method without executing it, and they are often used in functional programming constructs like streams.
There are four main types of method references:
Static Method References:
ClassName::staticMethodName
java// Lambda expression
Function<Integer, String> toStringLambda = (num) -> String.valueOf(num);
// Method reference
Function<Integer, String> toStringReference = String::valueOf;
Instance Method References on a Particular Instance:
instance::instanceMethodName
java// Lambda expression
Predicate<String> isEmptyLambda = (str) -> str.isEmpty();
// Method reference
String sampleString = "Hello, World!";
Predicate<String> isEmptyReference = sampleString::isEmpty;
Instance Method References on an Arbitrary Instance:
ClassName::instanceMethodName
java// Lambda expression
BiFunction<String, String, Boolean> startsWithLambda = (str, prefix) -> str.startsWith(prefix);
// Method reference
BiFunction<String, String, Boolean> startsWithReference = String::startsWith;
Constructor References:
ClassName::new
ClassName::new
java// Lambda expression
Supplier<List<String>> listSupplierLambda = () -> new ArrayList<>();
// Constructor reference
Supplier<List<String>> listSupplierReference = ArrayList::new;
javaimport java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class MethodReferencesExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// Using lambda expression
names.forEach(name -> System.out.println(name));
// Using method reference
names.forEach(System.out::println);
// Another example with an instance method reference
Consumer<String> printUpperCaseLambda = (str) -> System.out.println(str.toUpperCase());
Consumer<String> printUpperCaseReference = System.out::println;
printUpperCaseLambda.accept("hello");
printUpperCaseReference.accept("world");
}
}
In this example, the forEach
method of the List
interface is used to iterate over the elements of the list. The lambda expression (name -> System.out.println(name))
is equivalent to the method reference System.out::println
, which is more concise and often considered more readable. The example also demonstrates an instance method reference for the toUpperCase
method of the String
class.