After shying away from them for years, Java finally embraced functional programming constructs in the spring of 2014. Java 8 includes support for lambda expressions, and offers a powerful Streams API which allows you to work with sequences of elements, such as lists and arrays, in a whole new way.
In this tutorial, I'm going to show you how to create streams and then transform them using three widely used higher-order methods named map
, filter
and reduce
.
Creating a Stream
As you can tell from its name, a stream is just a sequence of items. Although there are lots of approaches to stream creation, for now, we'll be focusing only on generating streams from lists and arrays.
[author_more]
In Java 8, every class which implements the java.util.Collection
interface has a stream
method which allows you to convert its instances into Stream
objects. Therefore, it's trivially easy to convert any list into a stream. Here's an example which converts an ArrayList
of Integer
objects into a Stream
:
// Create an ArrayList
List<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(5);
myList.add(8);
// Convert it into a Stream
Stream<Integer> myStream = myList.stream();
If you prefer arrays over lists, you can use the stream
method available in the Arrays
class to convert any array into a stream. Here's another example:
// Create an array
Integer[] myArray = {1, 5, 8};
// Convert it into a Stream
Stream<Integer> myStream = Arrays.stream(myArray);
Continue reading %Java 8 Streams: An Intro to Filter, Map and Reduce Operations%
by Ashraff Hathibelagal via SitePoint
No comments:
Post a Comment