In a previous post, we saw how functional interfaces work, now let’s use them in the Stream API. This API was added in Java 8 release. A Stream, in it simplest form, is just a sequence of elements coming from a source and used to perform some action upon it. In this chapter, I’d like to demonstrate the use of Lambda in the Stream API.
About streams
If you’re already familiar with Streams, you can skip to the next chapter, if not, here’s a small introduction. In Java, a List is used to efficiently manage and access a bunch of items. It’s a datastore. A Stream on the other hand, is used for the consumption of items, coming from a datastore. Check out the following code:
1
2
3
4
5
6
List listStr = Arrays.asList("one","two","three","four");
Stream streamStr = listStr.stream().sorted();
List listStrSorted = streamStr.collect(Collectors.toList());
for (String str : listStrSorted) {
System.out.println(str);
}
First we make a list of Strings, and then we create a stream from it in order to sort them. From the result, we can make a new list, containing the sorted items. So it’s : List -> Stream -> do some stuff -> List again.
Here we sort the items, but we could also change, add, remove items, or execute aggregated functions upon them. The possibilities of Streams are endless, as you will see in the next chapters.