I just came across a question when using a List
and its stream()
method. While I know how to use them, I'm not quite sure about when to use them.
For example, I have a list, containing various paths to different locations. Now, I'd like to check whether a single, given path contains any of the paths specified in the list. I'd like to return a boolean
based on whether or not the condition was met.
This of course, is not a hard task per se. But I wonder whether I should use streams, or a for(-each) loop.
The List
private static final List<String> EXCLUDE_PATHS = Arrays.asList(
"my/path/one",
"my/path/two"
);
Example using Stream:
private boolean isExcluded(String path) {
return EXCLUDE_PATHS.stream()
.map(String::toLowerCase)
.filter(path::contains)
.collect(Collectors.toList())
.size() > 0;
}
Example using for-each loop:
private boolean isExcluded(String path){
for (String excludePath : EXCLUDE_PATHS) {
if (path.contains(excludePath.toLowerCase())) {
return true;
}
}
return false;
}
Note that the path
parameter is always lowercase.
My first guess is that the for-each approach is faster, because the loop would return immediately, if the condition is met. Whereas the stream would still loop over all list entries in order to complete filtering.
Is my assumption correct? If so, why (or rather when) would I use stream()
then?
new String[]{…}
here. Just useArrays.asList("my/path/one", "my/path/two")
– HolgerString[]
, there is no need to callArrays.asList
. You can just stream over the array usingArrays.stream(array)
. By the way, I have difficulties understanding the purpose of theisExcluded
test altogether. Is it really interesting whether an element ofEXCLUDE_PATHS
is literally contained somewhere within path? I.e.isExcluded("my/path/one/foo/bar/baz")
will returntrue
, as well asisExcluded("foo/bar/baz/my/path/one/")
… – HolgerArrays.stream
method, thanks for pointing that out. Indeed, the example I posted seems quite useless for anyone else besides me. I'm aware of the behaviour of theisExcluded
method, but it's really just something I need for myself, thus, to answer your question: yes, it is interesting for reasons I would like not to mention, as it would not fit into the scope of the original question. – mcuenez