java 同时迭代两个列表并使用流创建另一个列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48099358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:57:46  来源:igfitidea点击:

Iterate two lists simultaneously and create another using streams

javalambdajava-stream

提问by ParagJ

I want to achieve following using streams:

我想使用流实现以下目标:

List<MyObject> list1 = Arrays.asList(obj1, obj2, obj3);
List<Boolean> list2 = Arrays.asList(true, false, true);
List<MyObject> list = new ArrayList<>();
for(int i=0; i<list1.size();i++) {
     if(list2.get(i))
         list.add(list1.get(i));
}

Can anyone help? It should be easy but I am new to java streams.

任何人都可以帮忙吗?这应该很容易,但我是 Java 流的新手。

Note:The length of list1 and list2 would be same always.

注意:list1 和 list2 的长度总是相同的。

回答by user158037

You could do something like:

你可以这样做:

List<MyObject> list = IntStream.range(0, list1.size())
    .filter(i->list2.get(i))
    .map(i->list1.get(i))
    .collect(Collectors.toList())

It could be better if Java had build-in zipfor streams. For example with Guava you can use:

如果 Java 内置zip了流,那就更好 了。例如,您可以使用番石榴:

 Streams.zip(list2.stream(), list1.stream(), (a,b) -> a ? b : null)
    .filter(Objects::nonNull)
    .collect(Collectors.toList())