Java Functional Interface – Single method

Normally when we use interface define with a method, we need a class to implements it. With lambda, we can directly implements without a class.

Traditional way

Interface

public interface HelloService {
    public void sayHello(String text);
}

Implementation

public class HelloServiceImpl implements HelloService {

    @Override
    public void sayHello(String text) {
        System.out.println("Hello World, " + text);
    }

    public static void main(String[] args) {
        HelloService service = new HelloServiceImpl();
        service.sayHello(" Good morning");
    }
	
}

 

Java 8 Lambda

public class HelloServiceImpl  {

    public static void main(String[] args) {
	HelloService service = text -> System.out.println("Hello World! " + text);
	service.sayHello("Good morning");   
    }
}

 

Example 2:

Interface

public interface TimeUnitDifferent {
    long differentInMinutes(Calendar cal1, Calendar cal2)
}

Demo

public class TimeUnitTest {

  public static void main(String[] args) {
		
    TimeUnitTest demo = new TimeUnitTest();
		
    TimeUnitDifferent different = (Calendar cal1, Calendar cal2) -> { 
      return TimeUnit.MINUTES.convert(cal1.getTimeInMillis() - 
                                      cal2.getTimeInMillis(), 
                                      TimeUnit.MILLISECONDS); 
    };
		
    Calendar noon1pm = Calendar.getInstance();
    noon1pm.set(2016, 04, 11, 13, 00);
		
    Calendar noon12pm = Calendar.getInstance();
    noon12pm.set(2016, 04, 11, 12, 00);
		
    System.out.println("time minutes different: " + demo.check(noon1pm, noon12pm, different) );
		
  }
	
  private long check(Calendar cal1, Calendar cal2, TimeUnitDifferent different) {
    return different.differentInMinutes(cal1, cal2);
  }
}

 

 

 

Java Functional Interface – Single method

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.