【问题标题】:How to convert a List of one type to a List of another type using Streams? [duplicate]如何使用 Streams 将一种类型的列表转换为另一种类型的列表? [复制]
【发布时间】:2016-11-24 14:24:45
【问题描述】:

我想使用Streams 来实现以下目标:

我有 InputOutput 具有完全不同结构的对象的列表。

使用 for 循环,我可以将 List<Input> 转换为 List<Output>,如下所示:

for (Input input : listOfInput) {
    Output currentOutPutInstance = new Output();
    currentOutPutInstance.setArg1(input.getArg2());
    currentOutPutInstance.setArg2(input.getArg7());
    listOfOutPuts.add(currentOutPutInstance);
}

我尝试了这样的流:

private List<Output> getOutPutListFromInputList(List<Input> inPutList) {
    List<Output> outPutList = new ArrayList<Output>();
    outPutList = listOfPoolsInRun.stream.filter(<Somehow converting the input into output>)
                                 .collect(Collectors.toList()); 
}

注意:我不确定应该使用哪种Stream 方法。我使用filter 只是为了显示一些虚拟代码。

【问题讨论】:

  • 为什么是fillter
  • @Mritunjay :这只是一个例子,我不确定我可以在这里使用什么

标签: java java-8 java-stream


【解决方案1】:

使用map()Stream&lt;Input&gt; 转换为Stream&lt;Output&gt;

private List<Output> getOutPutListFromInputList(List<Input> inPutList)
{
    return listOfPoolsInRun.stream()
                           .map(input -> {
                                Output out = new Output();
                                out.setArg1(input.getArg2());
                                out.setArg2(input.getArg7());
                                return out;
                            })
                           .collect(Collectors.toList()); 
}

如果您在 Output 类中有适当的构造函数,这可以缩短:

private List<Output> getOutPutListFromInputList(List<Input> inPutList) 
{
    return listOfPoolsInRun.stream()
                           .map(input -> new Output(input.getArg2(),input.getArg7()))
                           .collect(Collectors.toList()); 
}

【讨论】:

  • 为了完整起见,由于必须处理输入以获得输出,它甚至可以更短为:return listOfPoolsInRun.stream().map(this::processInputs).collect (Collectors.toList());
  • 或者,根据情况和风格,如果输出知道如何从输入中实例化自己,它可以提供一个静态工厂方法,这样你就可以写map(Output::fromInput)
【解决方案2】:

将这部分代码设为方法:

OutPut createOutput(Input input) {
    OutPut currentOutPutInstance=new Output();
    currentOutPutInstance.setArg1(input.getArg2());
    currentOutPutInstance.setArg2(input.getArg7());
    return currentOutPutInstance;
}

然后map 就这样:

outPutList = listOfPoolsInRun.stream().map(this::createOutput).collect(Collectors.toList());

虽然没有必要使用专用方法createOutput,但我发现这样的代码更具可读性。

【讨论】:

    猜你喜欢
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 2023-01-04
    • 1970-01-01
    • 2011-03-05
    • 2021-11-12
    • 1970-01-01
    相关资源
    最近更新 更多