230.
MethodReferenceDemo::checkIfNumberGreaterThan8;
boolean flag = numberChecker.test(10);
}
}
Here, the MethodReferenceDemo class
has a static method
called checkIfNumberGreaterThan8(). This checks if the
input number is greater than 8
and returns a boolean value
accordingly. In the main method, a Predicate is defined.
However, instead of using a lambda
expression to implement the
Predicate, the existing checkIfNumberGreaterThan8() is
referenced via the method reference operator. Since
checkIfNumberGreaterThan8() is a static method,
the class
name followed by method name is used.
Consider the following Shape class:
public class Shape {
private String name;
}
What changes are required in this class in order to make the
code below valid?
List
shapeNames =
Arrays.asList(“Circle”,”Triangle”);
List shapes =
shapeNames.stream().map(Shape::new).collect(Collectors.t
oList());
Answer:
The code above creates a List of String values called
shapeNames. It then uses the Stream map() operation to create
231.
a List of Shape objects called shapes.
The code uses a
constructor reference to create a new Shape object using the
String shape name. So, the Shape
class requires a constructor
that accepts a String value as input as follows:
public Shape(String name) {
this.name = name;
}
Do'stlaringiz bilan baham: