Java 8 - LongFunction interface example

Posted on December 18, 2016


java.util.function.LongFunction is a functional interface whose functional method is R apply (long  value). The LongFunction interface represents an operation that takes a single argument of long type and returns a result R.

The following example shows how to use the apply () method of the LongFunction interface with lambda expression.

LongFunctionExample.java

package com.boraji.tutorail.lambda;

import java.util.Calendar;
import java.util.Date;
import java.util.function.LongFunction;

/**
 * @author imssbora
 */
public class LongFunctionExample {
   public static void main(String[] args) {
      // A function to check whether a given number is greater than zero or not.
      LongFunction<Boolean> function1 = (a) -> a > 0;

      System.out.println(function1.apply(50));
      System.out.println(function1.apply(-20));

      // A function to add number of days in current date and return new date.
      LongFunction<Date> addDays = (day) -> {
         Calendar calendar = Calendar.getInstance();
         calendar.add(Calendar.DAY_OF_MONTH, (int) day);
         return calendar.getTime();
      };

      System.out.println(addDays.apply(5));
      System.out.println(addDays.apply(50));
   }
}

Output

true
false
Fri Dec 23 17:24:53 IST 2016
Mon Feb 06 17:24:53 IST 2017