schrepfler
schrepfler

Reputation: 107

How to instantiate a Stream of String arrays by concatenating a single array with a Stream

Given a method with signature:

private String[] emitRecord(SomeType someType {...}

I would like to take theRecordAsStream defined as a stream of array of strings.

String[] someRecord = emitRecord(someType);
Stream<String[]> theRecordAsStream = Stream.of(someRecord);

and prepend it to and existing stream of arrays of string.

return Stream.concat(theRecordAsStream, eventsStream);

Unfortunately this is not possible as Stream.of(someRecord) returns a Stream which then triggers the following error on the concat.

Error:(118, 65) java: incompatible types: inference variable R has incompatible bounds
equality constraints: java.lang.String[]
lower bounds: T,java.lang.String[],java.lang.String,T

What's the proper way to deal with this?

Upvotes: 1

Views: 68

Answers (3)

Ali
Ali

Reputation: 97

It all depends what you want to do. If you would like to turn each element of the array into a string array, then what you need to do is as follows:

String[] array = {"hello", "world"};
Stream<String[]> stream = Arrays.stream(array).map(elem -> new String[]{elem});

And here is what it outputs:

stream.forEach(elem -> System.out.println(elem[0]));
hello
world

However, if you would like to create a stream which has only one element that is the result of the method, then you should do the following:

String[] array = {"hello", "world"};
Stream<String[]> stream = Stream.of(new String[][]{array});

And then in this case, in order to get the same result, you need to do the following:

stream.forEach(x -> Arrays.stream(x).forEach(System.out::println));

Upvotes: 0

Andreas
Andreas

Reputation: 159135

You explicitly tell Stream.of(T t) that you want a Stream<String[]>, i.e. you tell it that T is a String[]:

Stream<String[]> theRecordAsStream = Stream.<String[]>of(someRecord);

That way, the compiler cannot misinterpret it as call to Stream.of(T... values), with T being a String, which is what you're currently experiencing.

Upvotes: 4

sanver
sanver

Reputation: 114

You can wrap the return value as follows:

String[] a = new String[]{"hello", "world"};
Stream<String[]> b = Stream.of(new String[][]{a});

Upvotes: 3

Related Questions