Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate two lists simultaneously and create another using streams

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.

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

like image 294
ParagJ Avatar asked Jan 04 '18 16:01

ParagJ


1 Answers

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 zip for streams. For example with Guava you can use:

 Streams.zip(list2.stream(), list1.stream(), (a,b) -> a ? b : null)
    .filter(Objects::nonNull)
    .collect(Collectors.toList())
like image 78
user158037 Avatar answered Oct 16 '22 08:10

user158037