Create verbs on the fly
I
have a String[] for user input, and I want to filter the collection of devices based on whether the hostname of the device contains any user input.
I’m trying to keep up with class https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html do this.
interface PredicateOperation{
Predicate operation(String[] input);
}
public Predicate getPredicate(String[] input, PredicateOperation op){
return op.operation(input);
}
private TufinDeviceCollection<TufinDevice> filter(TufinDeviceCollection<TufinDevice> devices) {
Check if any HostNames of the devices contain any of the items in String[] modelContains
devices = devices.stream()
.sequential()
.filter(//How do i create this predicate?) we need to create the lamda expression to evaulate if the hostName of device d contains any of the items String[] userInput
.collect(Collectors.toCollection(TufinDeviceCollection<TufinDevice>::new));
}
It’s not clear to me how to define PredicateOperation in .filter(
….).
Solution
.filter(device -> Arrays.stream(userInput)
.anyMatch(input -> device.getHostName().contains(input)))
But you need the String[] userInput
method to be accessed from filter
.
I’m guessing it’s an attempt to write @FunctionalInterface
yourself instead of standard Predicate<T>
interface PredicateOperation {
Predicate operation(String[] input);
}
Although this is not very practical.
PredicateOperation operation = (String[] input) -> ((Object o) -> true);
Why do I need to return Predicate
if I can return results? A small enhanced version would be
interface PredicateOperation {
boolean operation(String[] input);
}
and
PredicateOperation operation = (String[] input) -> true;
Since Stream#filter
, it’s still not particularly useful for the Stream API, expecting a java.util.function.Predicate<T>
, not your favorite type.
And, yes, stop using the original Predicate