Java Reference
In-Depth Information
f)
Streams are objects that implement interface
Stream
and enable you to perform func-
tional programming tasks on
of elements.
g)
The intermediate stream operation
results in a stream containing only the el-
ements that satisfy a condition.
h) place the results of processing a stream pipeline into a collection such as a
List
,
Set
or
Map
.
i) Calls to
filter
and other intermediate streams are lazy—they aren't evaluated until an
eager operation is performed.
j)
Pattern
method
(new in Java SE 8) uses a regular expression to tokenize a
String
.
k)
Functional interfaces
must
contain only one method, but may also contain
methods and
static
methods that are fully implemented in the interface dec-
larations.
17.5
State whether each of the following is
true
or
false
. If
false
, explain why.
a)
An intermediate operation specifies tasks to perform on the stream's elements; this is
efficient because it avoids creating a new stream.
b)
Reduction operations take all values in the stream and turn them into a new stream.
c)
If you need an ordered sequence of
int
values, you can create an
IntStream
containing
such values with
IntStream
methods range and
rangeClosed
. Both methods take two
int
arguments representing the range of values. Method
rangeClosed
produces a se-
quence of values from its first argument up to, but not including, its second argument.
Method
range
produces a sequence of values including both of its arguments.
d)
Class
Files
(package
java.nio.file
) is one of many classes throughout the Java APIs
that have been enhanced to support
Stream
s.
e)
Interface
Map
does not contain any methods that return
Stream
s.
f)
The
Function
functional interface—which is used extensively in functional program-
ming—has methods
apply
(
abstract
),
compose
(
abstract
),
andThen
(
default
) and
identity
(
static
).
g)
If one class inherits the same
default
method from two interfaces, the class
must
over-
ride that method; otherwise, the compiler does not know which method to use, so it
generates a compilation error.
17.6
Write a lambda or method reference for each of the following tasks:
a) Write a lambda expression that receives two
double
parameters
a
and
b
and returns their
product. Use the lambda form that explicitly lists the type of each parameter.
b) Rewrite the lambda expression in Part (a) using the lambda form that does not list the
type of each parameter.
c) Rewrite the lambda expression in Part (b) using the lambda form that implicitly returns
the value of the lambda's body expression.
d) Write a no-argument lambda that implicitly returns the string
"Welcome
to
lambdas!"
.
e) Write a constructor reference for class
ArrayList
.
f) Reimplement the following statement using a lambda as the event handler:
button.addActionListener(
new
ActionListener()
{
public void
actionPerformed(ActionEvent event)
{
JOptionPane.showMessageDialog(ParentFrame.
this
,
"JButton event handler"
);
}
}
);