
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement DoubleSupplier Using Lambda and Method Reference in Java
DoubleSupplier interface is a built-in functional interface defined in java.util.function package. This functional interface doesn’t expect any input but produces a double-valued output. DoubleSupplier interface can be used as an assignment target for lambda expression and method reference. This interface contains only one abstract method: getAsDouble().
Syntax
@FunctionalInterface public interface DoubleSupplier { double getAsDouble(); }
Example of Lambda Expression
import java.util.concurrent.ThreadLocalRandom; import java.util.function.DoubleSupplier; public class DoubleSupplierLambdaTest { public static void main(String args[]) { DoubleSupplier getRandomDouble = () -> { // lambda expression double doubleVal = ThreadLocalRandom.current().nextDouble(0000, 9999); return Math.round(doubleVal); }; double randomVal = getRandomDouble.getAsDouble(); System.out.println("Random Double Generated : " + randomVal); System.out.println("Random Double Generated : " + getRandomDouble.getAsDouble()); System.out.println("Random Double Generated : " + getRandomDouble.getAsDouble()); } }
Output
Random Double Generated : 4796.0 Random Double Generated : 2319.0 Random Double Generated : 7403.0
Example of Method Reference
import java.util.function.DoubleSupplier; public class DoubleSupplierMethodRefTest { public static void main(String args[]) { DoubleSupplier random = Math::random; // method reference for(int i = 0; i < 5; ++i) { System.out.println("random number between 1 to 100: " + (random.getAsDouble() * 100) ); } } }
Output
random number between 1 to 100: 65.72186642095294 random number between 1 to 100: 42.389730890035146 random number between 1 to 100: 16.89589518236835 random number between 1 to 100: 45.85184122201681 random number between 1 to 100: 2.626718898776015
Advertisements