如何实现 ToDoubleFunction使用 Java 中的 lambda 表达式?
ToDoubleFunction<T> 是在 java.util.function 包中定义的一个函数接口。此函数接口需要一个参数作为输入,并生成一个double值的结果。它用作lambda 表达式 或方法 引用的赋值目标。ToDoubleFunction<T> 接口只包含一个抽象方法,applyAsDouble()。
语法
@FunctionalInterface public interface ToDoubleFunction<T> { double applyAsDouble(T value); }
示例 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")); } }
输出
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
示例 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 } }
输出
98.0 95.0 90.0 75.0 70.0
广告