如何使用flatMap实现这一点



我需要创建一个新的内部列表并使用它来设置外部列表。我该如何使用flatMap。fooList 是一个 FooDb 对象的列表,我从中创建 Foo 对象的列表。

final ArrayList<FooDb> fooList= getFooFromDB();    
final ArrayList<Foo> foos = new ArrayList<>();
fooList.forEach(foo -> {
final ArrayList<Bar> bars = new ArrayList<>();
item.getItems()
.forEach(item -> bars.add(new Bar(foo.getId(), foo.getName())));
foos.add(new Foo(0L, foo.getId(), bars));
});

你不需要flatMap.您有两个map操作:

  1. List<Item> -> List<Foo(..., ..., List<Bar>)>
  2. List<Item> -> List<Bar>前者所必需的。

List<Foo> foos = 
itemsList.stream()
.map(item -> new Foo(0L, item.getId(), item.getItems()
.stream()
.map(i -> new Bar(i.getId(), i.getName()))
.collect(Collectors.toList())))
.collect(Collectors.toList());

糟糕的格式,我已经使用 Stream API 几年了,从来没有写出一个好看的链。随意编辑。

你不需要FlatMap来做到这一点。必须使用FlatMap来展平数组的内容。在这种情况下,您需要 1 对 1 的映射,因此正确的方法是映射函数。

itemsList
.stream()
.map(item -> new Foo(0L,item.getId, item
.getItems()
.stream()
.map(item -> new Bar(item.getId(),item.getName())).collect(toList())));

相关内容

最新更新