Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Extract data from an object using peek() and map() methods
Let us start with a simple example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// {
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// }
long count = Stream.of(1, 2, 3, 4, 5).map(i -> i * i).count();
System.out.printf("This stream has %d elements", count);
//{
}
}
//}
Press desired key combination and then press ENTER.
Square each element in the above stream and print
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// {
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// }
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);
//{
}
}
//}
Press desired key combination and then press ENTER.
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().
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content