字符串和整数的连接流

Concat Stream of String and Integer

我正在学习 Stream,在一次这样的练习中,我试图通过以下代码加入 2 个不同类型的 String 和 Integer 流:

Stream<String> fruitStream = Stream.of("Apple", "Mango", "Muskmalon", "Guvava");
Stream<Integer> vegetablesStream = Stream.of(1, 2, 3, 4);

Stream<String> mixStream = Stream.concat(fruitStream, vegetablesStream.map(i -> i.toString()));
mixStream.forEach(System.out :: println);

它工作正常,给了我想要的结果。

然后我尝试使用方法参考:

Stream<String> mixStream = Stream.concat(fruitStream, vegetablesStream.map(Integer :: toString));

它开始抛出错误:

Wrong 1st argument type. Found: 'java.util.stream.Stream<java.lang.String>', required: 'java.util.stream.Stream<? extends T>'
concat (java.util.stream.Stream<? extends T>, java.util.stream.Stream<? extends T>) in Stream cannot be applied to (java.util.stream.Stream<java.lang.String>, java.util.stream.Stream<R>)   
reason: No compile-time declaration for the method reference is found

当我用 String :: ValueOf 替换我的方法参考时,它工作正常:

Stream<String> mixStream = Stream.concat(fruitStream, vegetablesStream.map(String :: valueOf));

I am unable to understand why Integer :: toString failed but String :: valueOf passed?

错误信息应该是Ambiguous method reference: both toString() and toString(int) from the type Integer are eligible。发生这种情况是因为 toStringtoString(int) 都可以在此处使用。

可能两者都是:

  .map(i -> i.toString(i))
  .map(i -> i.toString())      

它工作正常,因为 String::valueOf 没有这样的重载方法,因此编译器可以接受。