【问题标题】:How do I achieve this using a flatMap如何使用 flatMap 实现这一点
【发布时间】:2020-01-27 13:28:32
【问题描述】:

我需要创建一个新的内部列表并使用它来设置外部列表。如何使用 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));
            });

【问题讨论】:

  • 你的意思是,你有 Foo 类,它有 Bar 类的列表?因为在您的示例中不清楚 itemsList (foos?) 的含义。您能否提供这些类的结构?
  • 什么是itemsList?还有什么item.getItems()?共享的代码不会编译 item 作为不同上下文中的变量。
  • 实现什么?请编辑您的标题以使其完整,并总结您的具体技术问题。

标签: java java-8 java-stream flatmap


【解决方案1】:

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

  1. List&lt;Item&gt; -&gt; List&lt;Foo(..., ..., List&lt;Bar&gt;)&gt;,和
  2. List&lt;Item&gt; -&gt; List&lt;Bar&gt; 是前者所必需的。

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 几年了,从来没有写出好看的链。随意编辑。

【讨论】:

  • 第一个和第二个转换大多有不同的来源,除非实体类似于class Item { Collection&lt;Item&gt; items;...}
  • @Naman 很可能getItems() 返回List&lt;Item&gt;。让我们看看OP会说什么
【解决方案2】:

您不需要 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())));

【讨论】:

    猜你喜欢
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2014-11-03
    • 2014-12-16
    • 2012-01-24
    • 1970-01-01
    相关资源
    最近更新 更多