Introducing Java 8 Stream API
The Stream API is a new addition to the Collections API in Java 8. The Stream API brings new ways to process collections of objects. A stream represents a sequence of elements and supports different kinds of operations (filter, sort, map, and collect) from a collection. We can chain these operations together to form a pipeline to query the data, as shown in this diagram:
We can obtain a Stream from a collection using the .stream() method. For example, we have a dropdown of languages supported by the sample web application displayed in the header section. Let's capture this in an Array list, as follows:
List<String> languages = new ArrayList<String>();
languages.add("English");
languages.add("German");
languages.add("French");
If we have to print the list members, we will use a for loop in the following way:
for(String language : languages) {
System.out.println(language);
}
Using the streams API we can obtain the stream by calling the .stream() method on the languages array list and print the members in the following way:
languages.stream().forEach(System.out::println);
After obtaining the stream, we called the forEach() method, passing the action we wanted to take on each element, that is, output the member value on the console, using the System.out.println method.
Once we have obtained a Stream from a collection, we can use that stream to process the elements or members of the collection.