Using Stream.of
to create generic streams is very convenient, but what if I want to create a Stream<String[]>
of only one element?
Let’s say I have:
String[] tropicalFruits = new String[] {"pineapple", "banana", "mango"}; String[] fruits = new String[] {"melon", "peach", "apple"};
Then Stream.of(tropicalFruits, fruits)
produces a Stream<String[]>
of two elements. How can I achieve the same for a stream of a single element? If I try:
Stream<String[]> fruityStream = Stream.of(tropicalFruits);
I get:
Error: incompatible types: inference variable
T
has incompatible bounds
equality constraints:java.lang.String[]
lower bounds:java.lang.String
Stream<String[]> fruityStream = Stream.of(fruits); ^---------------^
I’ve googled for this and searched in SO but I got nothing. It seems to me that it’s not a very unusual or esoeteric problem, so it’s kind of surprising I didn’t get any answers (or I’m not searching with the right keywords).
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.
Use findFirst to return the first element of the Stream that passes your filters. It returns an Optional , so you can use orElse() to set a default value in case the Stream is empty. Save this answer.
A function is non-interfering when it does not modify the underlying data source of the stream, e.g. in the above example no lambda expression does modify myList by adding or removing elements from the collection.
Stream<String[]> stream = Stream.<String[]>of(tropicalFruits);
or
Stream<String[]> stream = Stream.of(new String[][]{tropicalFruits});
To produce a Stream<T>
, Stream.of
takes either T
or T...
.
A T[]
parameter perfectly applies to the second signature.
Therefore, passing a String[]
invokes the Stream.of(String...)
version.
To change this behaviour, we need to provide some extra information about T
(1) or define it more clearly (=unambiguously) (2).
There are two ideas came to my mind:
Stream.<String[]>of(new String[]{})
will produce a Stream<String[]>
.T[]
value in a T[][]
array to use the second signature.Stream.of(new String[][]{})
will produce a Stream<String[]>
.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