Java Reference
In-Depth Information
To use the Predicate interface, as with any generic type, we provide an actual type for the
parameter Camera , giving us (in this case) the parameterized type Predicate<Camera> ,
which is the following (although we don't have to write this out):
interface
interface Predicate
Predicate < Camera > {
boolean
boolean test ( Camera c );
}
So now our search application will be changed to offer us the following search method:
public
public List < Camera > search ( Predicate p );
Conveniently, this has the same “signature” as our own CameraAcceptor from the point of
view of the anonymous methods that lambdas implement , so the rest of our code doesn't have
to change! This is still a valid call to the search() method:
results = searchApp . search ( c -> c . isIlc () && c . getPrice () < 500 );
Here is the implementation of the search method:
functional/CameraSearchPredicate.java
public
public List < Camera > search ( Predicate < Camera > tester ) {
List < Camera > results = new
new ArrayList <>();
privateListOfCameras . forEach ( c -> {
iif ( tester . test ( c ))
results . add ( c );
});
return
return results ;
}
Suppose we only need the list to do one operation on each element, and then we'll discard it.
Upon reflection, we don't actually need to get the list back, but merely to get our hooks on
each element that matches our Predicate in turn.
Search WWH ::




Custom Search