如何创建Stream< String []>只有一个元素与Stream.of? [英] How can I create a Stream<String[]> with only one element with Stream.of?

查看:149
本文介绍了如何创建Stream< String []>只有一个元素与Stream.of?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Stream.of 创建通用流非常方便,但如果我想创建一个 Stream< String []> 只有一个元素?

Using Stream.of to create generic streams is very convenient, but what if I want to create a Stream<String[]> of only one element?

假设我有:

String[] tropicalFruits = new String[] {"pineapple", "banana", "mango"};
String[] fruits = new String[] {"melon", "peach", "apple"};

然后 Stream.of(tropicalFruits,fruits)生成两个元素的 Stream< String []> 。如何为单个元素的流实现相同的功能?如果我尝试:

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[]> fruittyStream = Stream.of(tropicalFruits);

我得到:


错误:不兼容的类型:推理变量 T 具有不兼容的
界限

等式约束: java。 lang.String []

下限: java.lang.String

Stream<String[]> fruittyStream = Stream.of(fruits);
                                 ^---------------^


我用Google搜索并搜索了但是我什么也没得到。在我看来,这不是一个非常不寻常或不太重要的问题,所以有点令人惊讶我没有得到任何答案(或者我没有用正确的关键词搜索)。

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

推荐答案

解决方案



Solution

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

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



解释



生成 Stream< T> Stream.of 采用 T T ...

A T [] 参数完全适用于第二个签名。

因此,传递 String [] 会调用 Stream.of(String ...)版本。

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.

要改变这种行为,我们需要提供一些关于 T (1)的额外信息,或者更清楚地定义它(=明确地说明) )(2)。

To change this behaviour, we need to provide some extra information about T (1) or define it more clearly (=unambiguously) (2).

我想到了两个想法:


  1. 指定方法的类型参数d明确地使用第一个签名。

    Stream。< String []> of(new String [] {})将产生一个 Stream< String []>

  2. 包装 T [] 使用第二个签名的 T [] [] 数组中的值。

    Stream.of(new String [] [ ] {})将产生 Stream< String []>

  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[]>.

这篇关于如何创建Stream&lt; String []&gt;只有一个元素与Stream.of?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆