nimo23 :
Is this (version 1):
public List<Task> getTasks(Set<Task> tasks, Predicate<? super Task> predicate) {
var stream = tasks.stream();
if (predicate != null) stream.filter(predicate);
// is the stream filtered if predicate != null ?
return stream.collect(Collectors.toList());
}
the same as this (version 2):
public List<Task> getTasks(Set<Task> tasks, Predicate<? super Task> predicate) {
var stream = tasks.stream();
// do I must reassign the stream to have the filtering
if (predicate != null) stream = stream.filter(predicate);
return stream.collect(Collectors.toList());
}
EDIT:
Only version 2 is correct, version 1 is incorrect.
Related question:
Is there a way to bypass an itermediate operation without using the solution of version 2? For example,
stream.filter(pred == null ? Void : predicate)
.order(comparator == null ? Void : comparator);
Jason :
No they are not the same. You have to do the re-assignment to Stream because filter doesn't mutate the underlying stream it creates a new Stream object. Very good question though.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=379071&siteId=1