Java 8 LongSupplier explained with code samples

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.

Edit

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 = -1689842518791524672Random 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.

Comments

Popular posts from this blog

How to use logging in SpringBoot with code samples

Python While Loop with code samples

How to convert a List to a Set