Java 8 Examples

Java 8 LongSupplier explained with code samples

Posted On
Posted By admin

In this blog post, I will be explaining how the Java 8 functional interface LongSupplier works. To know more about functional interfaces, you can refer this blog post.


The LongSupplier interface provides a method called getAsLong. This method does not accept any arguments. It returns a Long data type. The LongSupplier interface is a specialization of the Supplier interface that returns an Long. To see an example of the Supplier interface, refer to this blog post.

LongSupplier example

Consider the following code snippet:

LongSupplier getRandom = () ->  new Random().nextLong();
System.out.println("Random number 1 = "+getRandom.getAsLong());
System.out.println("Random number 2 = "+getRandom.getAsLong());

 

Here, we have implemented the LongSupplier.getAsLong method using a lambda expression. This getAsLong method simple returns a random integer less than 100. So when this code is executed, it will print output similar to the following:

Random number 1 = -1689842518791524672
Random number 2 = 8225865813273814162

You can get the source code for this example along with other code for other Java 8 examples at the Github repository here.

If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my new course Learn Java 8 New Features

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment