Create Stream<T> from single object

wondra :

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.

Eugene :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=447472&siteId=1