Reputation: 3583
How can you create Stream from single object? Such basic operation shown to be problematic in stream API. To illustrate, I would like to complete following method meaningfully
private Node parent;
private List<Node> children;
public Stream<Node> getFilteredNodes(Options o) {
if(o.findParent()/*special case*/) return /*??? stream containing just parent*/;
return children.stream().filter(x -> x.getName().equals(o.getQuery()));
}
or in other words, I would like something like LINQs return Enumerable.Repeat(parent,1);
. Even though storing parent
in a list with single item would work, it would also complicate other logic so I would prefer using built-in methods.
As for what I need it for - consistency of search API, so I could search up and down hierarchy(and combine both) with same method calls, piping it to next stage.
Upvotes: 28
Views: 18280
Reputation: 121048
There a method for that :
Stream.of(YourObject)
I am just wondering of you actually need the single element Stream here, since there is a Stream constructor that takes a var arg as argument, you can just return the stream of a single element or multiple ones by a single return statement.
Upvotes: 36