Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Stream<T> from single object

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.

like image 282
wondra Avatar asked Feb 16 '17 13:02

wondra


People also ask

How do you get a single element from a stream?

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.

How do you add an object to a stream?

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.

How do you update a single item in a List?

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.


1 Answers

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.

like image 131
Eugene Avatar answered Sep 19 '22 13:09

Eugene