如何通过将单个数组与流连接来实例化字符串数组流

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

给定一个带有签名的方法:

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

我想把theRecordAsStream定义为字符串数组流

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

并将其添加到现有的字符串数组流中。

return Stream.concat(theRecordAsStream, eventsStream);

不幸的是,这是不可能的,因为 Stream.of(someRecord) returns 一个 Stream 然后在 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

处理这个问题的正确方法是什么?

您可以按如下方式包装 return 值:

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

明确地告诉Stream.of(T t)你想要一个Stream<String[]>,即你告诉它T是一个String[] :

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

这样,编译器就不会将其误解为对 Stream.of(T... values) 的调用,而 TString,这就是您当前遇到的情况。

这完全取决于你想做什么。如果你想把数组的每个元素都变成一个字符串数组,那么你需要做的是:

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

这是它的输出:

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

但是,如果您想创建一个流,其中只有一个元素是该方法的结果,那么您应该执行以下操作:

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

然后在这种情况下,为了获得相同的结果,您需要执行以下操作:

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