Computer Science Courses
Related sites
Lab 7 |
To learn the functional programming style using the new Java languagesyntax (λ-expression) and library (Stream
APIs) to practive the adoption of Java SE 8.
In this part you will use the original programwhich is written in the "old", pre-Java8 style, with the aim of replacing the anonymous inner classes on lambda-expressions. This shouldhave immediate consequences in reducing the number of source files whichare required by the program. First, download the source code files(and the .txt
files whose name you should pass as the command-line argument to Assimilation
)
When you successfully perform the conversion of the original code into λ-expression based with utilisation of the streams API, the interfacesSelection.java
and Operation.java
will be no longer required.
Rewrite the code of Assimilation.java
by employing lambdas and streams of Java 8. The code of Individual.java
and Borg.java
do not require any change. In Assimilation.java
, first deal with mankind listing andselection processes, originally in Assimilation:65-66
andAssimilation:71-77
(lines of relevant code in the source file are shown). Your solution should include stream creation from list object mankind
, and stream operations forEach()
and filter()
. Think how to assign value to the consumer and predicate objects (in forEach
and filter
correspondingly). Once you've done with re-implementing the selection, you will see that the auxiliary method cull()
(Assimilate:16-25
) is no longer used and can be removed.
As the second step, re-implement using streams the conversion process Individual -> Borg
. Here, the stream operation ismap(..)
, which is run on a stream ofindividuals who passed the filter process Think whatjava.util.function.Function
is required here. Can it beinitialised as a lambda expression, or an existing method reference (which classand which method?) can be used? (Hint: both are possible.)Think how the Borg objects (which are the result of mapping individuals bymap(Individual -> Borg)
) can be collected back to a list for finalmerging with pre-existing Borg (this part, Assimilation:90
, needs no change). This has to be a terminal operation; more than one solution is possible.
Similar to the previous case, an auxiliary method convert()
(Assimilate:27-33
) is no longer required and can be removed.All-in-all, two methods and most of the loops gone! — significant reduction in the code size (in my solution, about 35%).
Lab 7 |
Updated: Sun 12 Jun 2016 17:27:37 AEST • Responsible Officer: JavaScript must be enabled to display this email address. • Page Contact:
+61 2 6125 5111
The Australian National University, Canberra
CRICOS Provider : 00120C ABN : 52 234 063 906