Java LongSupplier Example
May 05, 2020
This page will walk through LongSupplier
example. The LongSupplier
is the functional interface introduced in Java 8 under the java.util.function
package. The LongSupplier
is the long-producing primitive specialization of Supplier
functional interface. The functional method of LongSupplier
is getAsLong()
which returns result of long
datatype. Find the LongSupplier
structure from Java doc.
@FunctionalInterface public interface LongSupplier { long getAsLong(); }
LongSupplier
can be instantiated using lambda expression and method reference. Here we will provide using LongSupplier
in our applications in detail.
Using Lambda Expression
Find the code to instantiateLongSupplier
using lambda expression.
LongSupplierWithLE.java
package com.concretepage; import java.time.LocalDate; import java.util.function.LongSupplier; public class LongSupplierWithLE { public static void main(String[] args) { LongSupplier epochLs = () -> LocalDate.now().toEpochDay(); System.out.println(epochLs.getAsLong()); LongSupplier ls = () -> Long.parseLong("145"); System.out.println(ls.getAsLong()); LongSupplier multiplyLs = () -> { long num1 = 30L; long num2 = 50L; return num1 * num2; }; System.out.println(multiplyLs.getAsLong()); } }
18387 145 1500
Using Method Reference
Find the code to instantiateLongSupplier
using method reference.
LongSupplierWithMR.java
package com.concretepage; import java.util.Date; import java.util.function.LongSupplier; public class LongSupplierWithMR { public static void main(String[] args) { LongSupplier timeLs = new Date()::getTime; System.out.println(timeLs.getAsLong()); LongSupplier dataLs = AppUtil::noOfData; System.out.println(dataLs.getAsLong()); } } class AppUtil { public static long noOfData() { return 1234L; } }
1588686047879 1234
Passing as Method Parameter
Here we will passLongSupplier
as method parameter.
WithMethodParameter.java
package com.concretepage; import java.util.Random; import java.util.function.LongSupplier; import java.util.stream.LongStream; public class WithMethodParameter { public static void main(String[] args) { String id = createTempId(() -> new Random().nextLong()); System.out.println(id); System.out.println("--- With LongStream.generate() ---"); LongStream longStream = LongStream.generate(() -> new Random().nextLong()).limit(5); longStream.forEach(v -> System.out.println(v)); } static String createTempId(LongSupplier ls) { return "temp-id-" + ls.getAsLong(); } }
temp-id-4388374608979425584 --- With LongStream.generate() --- -4744270447427209101 7914465496616666323 1365939277194664766 6155062943727281293 -1048509395104587980