简体   繁体   English

在列表上迭代一次,但返回两个列表

[英]Iterate once over list, but return two lists

I have a List<Foo> : foos .我有一个List<Foo>foos And I have two methods that return Bar : Bar doThingOne(Foo foo) and Bar doThingTwo(Foo foo) .我有两种返回Bar方法: Bar doThingOne(Foo foo)Bar doThingTwo(Foo foo) I want to end up with two List<Bar> s – one by iterating over foos and applying doThingOne() to each Foo , and the other by doing the same thing but with doThingTwo() .我想最终得到两个List<Bar> foos一个通过迭代foos并将doThingOne()应用于每个Foo ,另一个通过做同样的事情但使用doThingTwo() Is it possible to do this without iterating over foos twice?是否可以在不迭代foos两次的情况下执行此foos

Isn't it what you want?这不是你想要的吗? It's so simple that I have some doubt.太简单了,让我有些怀疑。

List<Bar> lb1 = new ArrayList<Bar>();
List<Bar> lb2 = new ArrayList<Bar>();
for (Foo f : foos) {
    lb1.add(doThingOne(f));
    lb2.add(doThingTwo(f));
}

You can do this with stream :你可以用流来做到这一点:

List<Bar> barList1 = new ArrayList<>();
List<Bar> barList2 = fooList.stream().peek(f -> barList1.add(doThingOne(f))
    .map(f -> doThingTwo(f)).collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM