Java Reference
In-Depth Information
In Example 9-1 , we have a list of Hero objects representing superheroes through the ages.
We use the Stream mechanism to filter just the adult heros, and sum their ages. We then use
it again to sort the heros' names alphabetically.
In both operations we start with a stream generator ( Arrays.stream() ), run it through sev-
eral steps, one of which involves a mapping operation (don't confuse with java.util.Map !)
that causes a different value to be sent along the pipeline, followed by a terminating opera-
tion. The map and filter operations almost invariably are controlled by a lambda expression
(inner classes would be too tedious to use in this style of programming!).
Example 9-1. SimpleStreamDemo.java
static
static Hero [] heroes = {
new
new Hero ( "Grelber" , 21 ),
new
new Hero ( "Roderick" , 12 ),
new
new Hero ( "Francisco" , 35 ),
new
new Hero ( "Superman" , 65 ),
new
new Hero ( "Jumbletron" , 22 ),
new
new Hero ( "Mavericks" , 1 ),
new
new Hero ( "Palladin" , 50 ),
new
new Hero ( "Athena" , 50 ) };
public
public static
static void
void main ( String [] args ) {
long
long adultYearsExperience = Arrays . stream ( heroes )
. filter ( b -> b . age >= 18 )
. mapToInt ( b -> b . age ). sum ();
System . out . println ( "We're in good hands! The adult superheros have " +
adultYearsExperience + " years of experience" );
List < Object > sorted = Arrays . stream ( heroes )
. sorted (( h1 , h2 ) -> h1 . name . compareTo ( h2 . name ))
. map ( h -> h . name )
. collect ( Collectors . toList ());
System . out . println ( "Heroes by name: " + sorted );
}
And let's run it to be sure it works:
We're in good hands! The adult superheros have 243 years of experience
Heroes by name: [Athena, Francisco, Grelber, Jumbletron, Mavericks, Palladin,
Roderick, Superman]
Search WWH ::




Custom Search