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.
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())
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With