Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Elements from a list based on another list [duplicate]

Tags:

java

java-8

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?

like image 649
Karthik Avatar asked Aug 04 '15 12:08

Karthik


1 Answers

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());
like image 108
Eran Avatar answered Oct 31 '22 21:10

Eran