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.
To find an element matching specific criteria in a given list, we: invoke stream() on the list. call the filter() method with a proper Predicate. call the findAny() construct, which returns the first element that matches the filter predicate wrapped in an Optional if such an element exists.
To insert an element at the end of a stream, we need to change the order in which the arguments were passed to the Stream. concat() method. Now the resultant stream from the given element is passed as the second parameter to the Stream. concat() method.
To update or set an element or object at a given index of Java ArrayList, use ArrayList. set() method. ArrayList. set(index, element) method updates the element of ArrayList at specified index with given element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With