Method references are the special form of Lambda expression. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, this way is often clearer to refer to existing method by name. They are more compact and easy-to-ready to express something.
Basically, this is just shorthand syntax for a Lambda Expression but this version is more concise & readable.
Types of Method reference
There are four types of method reference.
Reference to a static method
@Test
public void testReferenceStaticMethod()
{
Function<String, String> upperFunc = StringUtils::toUpperCase;
Assert.assertEquals("HI JAVA", upperFunc.apply("hi Java"));
}
Reference to an instance method of a particular object
@Test
public void testInstanceMethod()
{
String text = "hi java";
Supplier<Integer> getLength = text::length;
Assert.assertEquals(Integer.valueOf(7), getLength.get());
}
Reference to an instance method of a particular type
@Test
public void testInstanceMethodByType()
{
Function<String, String> upperFunc = String::toLowerCase;
Assert.assertEquals("hi java", upperFunc.apply("hi Java"));
}
Reference to a constructor
@Test
public void testCallConstructor()
{
Function<Integer, Integer> f = Integer::new;
Assert.assertEquals(new Integer(99), f.apply(99));
}
Conclusion
In conclusion, if possible, we should try to use method references can make our code cleaner, more readable & promote code reusability, but they have some restrictions on some cases.
No comments:
Post a Comment