Java Reference
In-Depth Information
} else {
This approach is safer and cleaner in that it requires the user to be more intentional about error
handling, while also giving them the information necessary to perform that error handling. It also allows
you to handle errors while the stream is being processed, instead of having to wait until afterwards. The
downside of this approach is that it is not as easy to wrap existing resource-based code: you have to wrap
your results in the Result object in the first place, as opposed to wrapping the whole method that you are
trying to implement in some helper object.
When you are working with resources in Java, you are working with syntactic sugar of a different flavor:
it is not especially kind to post-functional code, but it was a very nice benefit for the imperative code that
came before it. Your particular approach to bridging the paradigm depends on the needs of your particular
system, but the sooner you can encapsulate the ugliness and move entirely into the post-functional world,
the happier your code will be.
Bridging Collections and Streams
Before Java introduced streams, its primary bulk mode of operation was through the Collection API. There
were efforts to create bulk collection operations (called “comprehensions”), and even some efforts to turn
the Iterator class into something strongly resembling the contemporary stream. However, the API is really
not intended for post-functional kinds of work, and there were consistently rough edges that worked poorly
with the stream approach: this is why Java introduced an entirely new set of APIs.
The good news is that it is easy to go from an instance of the collection type to a stream: simply call
the or collection.parallelStream() method for a sequential or parallel stream,
respectively. For an instance of the Map type, you will first need to specify whether you want the map's key
set, entry set, or values collection, and then you can get the stream of your choice from there. Both the Map
type and the Collection type also have a forEach method that takes a consumer: it is effectively a shorthand
for , and this method should probably supplant your for loops in
any case when you do not need to know the index.
Going from a stream back to a collection, however, is somewhat trickier. There is no .toList()
method on the Stream type, as nice as that would be. One option is to use one of the methods of converting
the stream into an array, and then using Arrays.asList(Array) to get your desired list. The result will be a
fixed-sized (but not immutable) list of all the stream elements. A basic demonstration of that approach
is given in Listing 7-7, and if that is the approach that you want to take, be sure to read the next section
on arrays.
Search WWH ::

Custom Search