如何在Java中使用Lambda表达式实现ToDoubleFunction <T>?
ToDoubleFunction <T>是java.util.function包中定义的功能接口 。该功能接口期望参数作为输入并产生双值结果。它用作lambda表达式 或方法 引用的分配目标。ToDoubleFunction <T> 接口仅包含一种抽象方法applyAsDouble()。
语法
@FunctionalInterfacepublic 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("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.0The 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.095.0
90.0
75.0
70.0
以上是 如何在Java中使用Lambda表达式实现ToDoubleFunction <T>? 的全部内容, 来源链接: utcz.com/z/341003.html