1/13/2019

[Java8] Method References

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.

1 comment:

  1. CASINO: JARIZO RESORT - LAS VEGAS NV - KTNV
    JARIZO 하남 출장안마 RESORT in 제주 출장안마 LAS VEGAS NV - Find 김해 출장마사지 your next Vegas hotel room or suite at JARIZO RESORT in Las Vegas, NV. Click here 부산광역 출장마사지 for more 세종특별자치 출장안마 details.

    ReplyDelete