Java Reference
In-Depth Information
In solution 1, a
Comparator
is generated, by which the
Player
objects will be
evaluated for the number of goals scored (
getGoals
). A stream is then generated
from a
List<Player>
that is referenced as team. The stream provides the
sor-
ted()
function, which accepts a
Comparator
by which to perform a sort on a
stream of data. The
Comparator
that was initially generated is passed to the
sor-
ted()
function, and then the
map()
function is called upon the result. The
map()
function provides the ability to map expressions to each element within the stream.
Therefore, within the map, this solution utilizes a lambda expression to create a string
that contains each
Player
object's
firstName
,
lastName
, and
goals
fields.
Lastly, since the
List<Player>
is an iterable, it contains the
forEach()
method.
The
forEach()
method enables an expression or group of statements to be applied
to each element within the list. In this case, each element in the list is printed to the
command line. As such, since the
map()
function was applied to the stream, each ele-
ment in the list is subsequently printed per the algorithm applied within the
map()
.
Therefore, the result is that the players first and last names along with the number of
goals each has scored will be printed at the command line.
Solution 2 uses a different technique to accomplish a similar task. In the second
solution, the
Collections.sort()
method is invoked on the list. The first argu-
ment to
Collections.sort()
is the list itself, and the second argument is the
comparison implementation in the form of a lambda expression. The lambda expres-
sion in this case has two parameters passed to it, both
Player
objects, and it com-
pares the
lastName
of the first player to the
lastName
of the second player. There-
fore, the sort will be performed on the
lastName
field of the
Player
object, in as-
cending order. To finish off solution 2, the sorted list is printed out. To do this a stream
is generated from the sorted list, and the
forEach()
method is then invoked on the
stream of data, printing out each player's
lastName
.
No doubt, the lambda expression greatly reduces the amount of code required to
sort collections of data. It also makes it easy to understand the logic behind the sort, as
readability is much easier than trying to follow looping implementations of the past.
6-4. Specifying Filter Criteria on a Col-
lection of Data
Problem