Back
Close

Extract Data from a Stream

Harinath
2,018 views

Extract data from an object using peek() and map() methods

Let us start with a simple example

// {...}
long count = Stream.of(1, 2, 3, 4, 5).map(i -> i * i).count();
System.out.printf("This stream has %d elements", count);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Square each element in the above stream and print

// {...}
long count = Stream.of(1, 2, 3, 4, 5)
.map(i -> i * i)
.peek(i -> System.out.printf("%d ", i))
.count();
System.out.printf("%nThe stream has %d elements", count);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

The map() operation in the stream applies the given lambda function(i - > i * i) as an argument on the elements of the stream. The count method returns the value 5. To Print the square value of each value in the stream, we used intermediate method peek().

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants