Java Reference
In-Depth Information
Mapping 34438929 to string
34438929
Mapping 34438930 to string
34438930
*/
// Parallel stream—commonly requires explicit call to .parallel()
stream = IntStream.range(1, Integer.MAX_VALUE);
stream.parallel().mapToObj(i -> {
System.out.println("Mapping " + i + " to string");
return Integer.toString(i);
}
).forEach(System.out::println);
/* Example output sampling
Mapping 298035702 to string
298035702
Mapping 298035703 to string
298035703
Mapping 298035704 to string
298035704
Mapping 298035705 to string ¬ Thread change
Mapping 405565 to string
405565
Mapping 405566 to string
405566
Mapping 405567 to string
405567
*/
}
}
There are a number of ways to implement spliterators in Java 8. Most of the functionality for creating
spliterators is contained within the Spliterators (note the “s”) class. Another common way to create
a spliterator is to start with a stream and call stream.spliterator() . The final common way to create
a spliterator is to build it from an iterator, which we will explore in the next section. In this section, we
implement a spliterator using the AbtractSpliterator base class provided within the Spliterators class. We will
then use that result to construct the stream.
The core method to implement for the AbstractSplitorator base class is tryAdvance . This method
takes a Consumer , which represents the downstream behavior. The code is responsible passing any newly
generated element into the consumer. The method returns true if a new element was generated, and
returns false if it is exhausted.
We do not want to tie this code directly into our particular implementation. We don't want this for two
reasons: first, we'd like to simplify our classes and maintain clear distinctions in our code; second, by staying
focused, we will create a valuable bit of reusable code. In that case, our class can rely on the user to specify
the transformation. Since almost every interesting method on the ResultSet type throws a SQLException,
we can't take a simple functional interface: instead, we will provide an abstract method that throws a
SQLException, and then handle the exception in our tryAdvance method. Assuming our class has the
ResultSet stored in a field named resultSet , then the resulting methods are given in Listing 5-9.
Search WWH ::




Custom Search