Java Reference
In-Depth Information
You have a list of data to which you'd like to apply some filtering so that you can ex-
tract objects meeting the specified filter criteria.
Solution
Create a stream from the list of data and apply a filter, passing the desired predicate.
Finally, add each of the objects matching the specified filter criteria to a new list. In the
following example, a list of Player objects is being filtered to capture only those
players who have scored ten or more goals.
team.stream().filter(
p -> p.getGoals() >= 10
&& p.getStatus() == 0)
.forEach(element -> gteTenGoals.add(element));
System.out.println("Number of Players Matching Criteria:
" + gteTenGoals.size());
How It Works
The solution to this recipe makes use of a data stream since it contains an easy-to-use
filter function. The collection of data, team , generates a stream, and then the filter
function is called upon it, accepting a predicate by which to filter the data within the
collection. The predicate is written in the form of a lambda expression that contains
two such filtering criteria. The lambda expression passes a Player object as an argu-
ment, and then filters the data based upon the number of goals being greater than or
equal to ten and an active status.
Once the data has been filtered, the forEach() method is used to add each of the
elements that meet the filtering criteria to a list. This is also done using a lambda ex-
pression. The element to be added to the list is passed to the lambda expression as an
argument, and it is subsequently added to the list within the body of the expression.
Lambda expressions are very well suited for working within stream functions. Not
only do they enable easier development of business logic, but they also make collec-
tions filtering easier to read and maintain.
6-5. Implementing Runnable
Search WWH ::




Custom Search