Java Reference
In-Depth Information
Processing the Stream Pipeline
When forEach is called (line 58), the stream pipeline is processed. First, line 55 produces
an intermediate IntStream containing only the odd values. Next, line 56 multiplies each
odd integer by 10 . Then, line 57 sorts the values and line 58 displays each element.
17.3.6 Creating Streams of int s with IntStream Methods range and
rangeClosed
If you need an ordered sequence of int values, you can create an IntStream containing such
values with IntStream methods range (line 63 of Fig. 17.5) and rangeClosed (line 67).
Both methods take two int arguments representing the range of values. Method range
produces a sequence of values from its first argument up to, but not including its second
argument. Method rangeClosed produces a sequence of values including both of its argu-
ments. Lines 63 and 67 demonstrate these methods for producing sequences of int values
from 1-9 and 1-10, respectively. For the complete list of IntStream methods, visit:
http://download.java.net/jdk8/docs/api/java/util/stream/
IntStream.html
17.4 Stream<Integer> Manipulations
[This section demonstrates how lambdas and streams can be used to simplify programming
tasks that you learned in Chapter 7, Arrays and ArrayLists.]
Just as class IntStream 's method of can create an IntStream from an array of int s, class
Array 's stream method can be used to create a Stream from an array of objects.
Figure 17.6 performs filtering and sorting on a Stream<Integer> , using the same tech-
niques you learned in Section 17.3. The program also shows how to collect the results of a
stream pipeline's operations into a new collection that you can process in subsequent state-
ments. Throughout this example, we use the Integer array values (line 12) that's initial-
ized with int values—the compiler boxes each int into an Integer object. Line 15 displays
the contents of values before we perform any stream processing.
1
// Fig. 17.6: ArraysAndStreams.java
2
// Demonstrating lambdas and streams with an array of Integers.
3
import java.util.Arrays;
4
mport java.util.Comparator;
i
5
import java.util.List;
6
7
8
import java.util.stream.Collectors;
public class ArraysAndStreams
9
{
10
public static void main(String[] args)
11
{
12
Integer[] values = { 2 , 9 , 5 , 0 , 3 , 7 , 1 , 4 , 8 , 6 };
13
14
// display original values
15
System.out.printf( "Original values: %s%n" , Arrays.asList(values));
Fig. 17.6 | Demonstrating lambdas and streams with an array of Integer s. (Part 1 of 2.)
 
 
Search WWH ::




Custom Search