Java Reference
In-Depth Information
Streams and Object Serialization, in which a program reads a stream of bytes from a file
or outputs a stream of bytes to a file. As you'll see in Section 17.7, you also can use func-
tional programming to manipulate the contents of a file.
[This section demonstrates how lambdas and streams can be used to simplify programming
tasks that you learned in Chapter 7, Arrays and ArrayLists.]
Figure 17.5 demonstrates operations on an
IntStream
(package
java.util.stream
)—a
specialized stream for manipulating
int
values. The techniques shown in this example also
apply to
LongStream
s
and
DoubleStream
s
for
long
and
double
values, respectively.
1
// Fig. 17.5: IntStreamOperations.java
2
// Demonstrating IntStream operations.
3
import
java.util.Arrays;
4
5
6
import
java.util.stream.IntStream;
public class
IntStreamOperations
7
{
8
public static void
main(String[] args)
9
{
10
int
[] values = {
3
,
10
,
6
,
1
,
4
,
8
,
2
,
5
,
9
,
7
};
11
12
// display original values
13
System.out.print(
"Original values: "
);
14
IntStream.of(values)
.forEach(value -> System.out.printf(
"%d "
, value));
15
16
System.out.println();
17
18
// count, min, max, sum and average of the values
19
System.out.printf(
"%nCount: %d%n"
,
IntStream.of(values).count()
);
20
System.out.printf(
"Min: %d%n"
,
21
IntStream.of(values).min().getAsInt()
);
22
System.out.printf(
"Max: %d%n"
,
23
IntStream.of(values).max().getAsInt()
IntStream.of(values).sum()
);
24
System.out.printf(
"Sum: %d%n"
,
);
25
System.out.printf(
"Average: %.2f%n"
,
26
IntStream.of(values).average().getAsDouble()
);
27
28
// sum of values with reduce method
29
System.out.printf(
"%nSum via reduce method: %d%n"
,
30
IntStream.of(values)
.reduce(
0
, (x, y) -> x + y)
31
);
32
33
// sum of squares of values with reduce method
34
System.out.printf(
"Sum of squares via reduce method: %d%n"
,
35
IntStream.of(values)
.reduce(
0
, (x, y) -> x + y * y)
36
);
Fig. 17.5
|
Demonstrating
IntStream
operations. (Part 1 of 2.)