Stream.of(1,2,3)怎么处理返回List<Foo(1,"1")>

描述:

Stream传入一组数字然后处理得到其他类型的输出

等效以下代码:

//method
List<Foo> fooList = new ArrayList<>();
for (Integer i: Arrays.asList(1, 2, 3)) {
    fooList.add(new Foo(i, i.toString()));
}
return fooList;
//method
//Foo类
class Foo(int i, String s){}

搜了下没找到类似这种的,一般都是输入输出一致那种.

阅读 2.4k
1 个回答

问题解决了
使用Stream.map(Function<T, R>)来处理.
integer是输入, new Foo(integer, integer.toString())是输出.

List<Foo> foos = Stream.of(1, 2, 3).map(integer -> new Foo(integer, integer.toString())).collect(Collectors.toList());
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题