- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement ToDoubleFunction using lambda expression in Java?
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
Advertisements
To Continue Learning Please Login
Login with Google