By writing applications in Java there are many use cases for java.util.Collection
.
Since java.util.stream.Stream
was introduced with Java 8, I came over some use-cases where it is difficult to decide what to use.
For example: You are going to write some util-methods.
public static List<?> filterHashToList(int hash, Collection<?> toFilter) {
return toFilter.stream()
.filter((Object o) -> hash == o.hashCode())
.collect(Collectors.toCollection(LinkedList::new));
}
What about writing it like this:
public static List<?> filterHashToList(int hash, Collection<?> toFilter) {
List<Object> result = new LinkedList<>();
for(Object o : toFilter) {
if(hash == o.hashCode()) {
result.add(o);
}
}
return result;
}
Both methods would produce the same result. java.util.stream.Stream
and java.util.stream.Collector
are interfaces, so the implementation can vary as well if I use custom streams and collectors.
I think there are loads of implementations out there using the old-fashoined loop-way.
So, is it possible to answer what to use, stream or loop, by use-case? And if so, do all implementations have to be updated where appropriate?
Or should I even provide both ways by implementing util-methods? Or should I also provide a mthed returning the stream after the filtering process so you can work with that one too if required?