ToDoubleFunction <T>是java.util.function包中定义的功能接口 。该功能接口期望参数作为输入并产生双值结果。它用作lambda表达式 或方法 引用的分配目标。ToDoubleFunction <T> 接口仅包含一种抽象方法applyAsDouble()。
@FunctionalInterface public interface ToDoubleFunction<T> { double applyAsDouble(T value); }
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("nhooo")); 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")); } }
输出结果
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
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 } }
输出结果
98.0 95.0 90.0 75.0 70.0