I want to do this in Java 8
I have a Boolean list and another Object list, size of these two lists is always same. I want to remove all the elements from object list, which have false at the corresponding index in boolean list.
I will try to explain with an example:
objectList = {obj1,obj2,obj3,obj4,obj5};
booleanList = {TRUE,FALSE,TRUE,TRUE,FALSE};
So from these list, I want to change objectList to
{obj1,obj3,obj4}// obj2 and obj5 are removed because corresponding indices are `FALSE` in `booleanList`.
If I have have do this in Java 7, I would do the following :
List<Object> newlist = new ArrayList<>();
for(int i=0;i<booleanList.size();i++){
if(booleanList.get(i)){
newList.add(objectList.get(i));
}
}
return newList;
Is there a way to do this in Java 8 with lesser code?
You can use an IntStream to generate the indices, and then filter to get the filtered indices and mapToObj to get the corresponding objects :
List<Object> newlist =
IntStream.range(0,objectList.size())
.filter(i -> booleanList.get(i))
.mapToObj(i -> objectList.get(i))
.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