Applying an action to every element of a stream
In this recipe, you will learn how to apply an action to all the elements of the stream. We will use three methods: two terminal operations, the forEach()
and forEachOrdered()
, and an intermediate operation, the peek()
method.
Getting ready
The example of this recipe has been implemented using the Eclipse IDE. If you use Eclipse or other IDE such as NetBeans, open it and create a new Java project.
How to do it...
Follow these steps to implement the example:
- First, we will implement some auxiliary classes we will use in the example. Create a class named
Person
with the basic characteristics of a person. Check the Creating streams from different sources recipe to see the source code of this class. - As we'll work with methods that depend on the order of the elements of the stream, we have to override some methods in the
Person
class. First, we'll override thecompareTo()
method that compares two persons. We'll create a staticComparator
object using...