How to implement ToDoubleFunction<T> using lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

ToDoubleFunction<T> is a functional interface defined in java.util.function package. This functional interface expects a parameter as input and produces a double-valued result. It is used as an assignment target for a lambda expression or method reference. ToDoubleFunction<T> interface contains only one abstract method, applyAsDouble().

Syntax

@FunctionalInterface
public interface ToDoubleFunction<T> {
   double applyAsDouble(T value);
}

Example-1

import java.util.function.ToDoubleFunction;

public class ToDoubleFunctionTest1 {
   public static void main(String args[]) {
      ToDoubleFunction<String> strLength = s -> s.length();    // lambda expression
      System.out.println("The length of a given String using lambda expression is: " + strLength.applyAsDouble("TutorialsPoint"));

      ToDoubleFunction<String> innerClassImplementation = new ToDoubleFunction<String>() {
         @Override // anonymous inner class
         public double applyAsDouble(String value) {
            return value.length();
         }
      };
      System.out.println("The length of a given string using anonymous inner class is: " + innerClassImplementation.applyAsDouble("Tutorix"));
   }
}

Output

The length of a given String using lambda expression is: 14.0
The length of a given string using anonymous inner class is: 7.0


Example-2

import java.util.*;
import java.util.stream.*;
import java.util.function.ToDoubleFunction;

public class ToDoubleFunctionTest2 {
   public static void main(String[] args) {
      List<String> marksList = new ArrayList<String>();
      marksList.add("98");
      marksList.add("95");
      marksList.add("90");
      marksList.add("75");
      marksList.add("70");

      ToDoubleFunction<String> function = (String score) -> Double.valueOf(score); // lambda
      marksList.stream()
         .mapToDouble(function)
         .forEach(System.out::println);    // method reference
   }
}

Output

98.0
95.0
90.0
75.0
70.0
raja
Published on 09-Jan-2020 09:58:09
Advertisements