Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a Stream<String[]> with only one element with Stream.of?

Tags:

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).

like image 773
Alf Avatar asked Feb 05 '18 15:02

Alf


People also ask

How do I get one element from a stream list?

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 I return a stream string?

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.

Can we modify source of stream of lambda expression in stream operation?

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.


1 Answers

Solution

Stream<String[]> stream = Stream.<String[]>of(tropicalFruits); 

or

Stream<String[]> stream = Stream.of(new String[][]{tropicalFruits}); 

Explanation

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:

  1. To specify a type argument of the method explicitly to use the first signature.
    Stream.<String[]>of(new String[]{}) will produce a Stream<String[]>.
  2. To wrap a T[] value in a T[][] array to use the second signature.
    Stream.of(new String[][]{}) will produce a Stream<String[]>.
like image 123
Andrew Tobilko Avatar answered Sep 22 '22 15:09

Andrew Tobilko