简体   繁体   English

从列表中过滤元素基于另一个列表

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

I want to do this in Java 8 我想在Java 8中这样做

I have a Boolean list and another Object list, size of these two lists is always same. 我有一个Boolean列表和另一个Object列表,这两个列表的大小始终相同。 I want to remove all the elements from object list, which have false at the corresponding index in boolean list. 我想从object列表中删除所有元素,它们在boolean列表中的相应索引处具有false

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 所以从这些列表中,我想将objectList更改为

{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 : 如果我已经在Java 7执行此操作,我将执行以下操作:

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? 有没有办法在Java 8使用较少的代码执行此操作?

You can use an IntStream to generate the indices, and then filter to get the filtered indices and mapToObj to get the corresponding objects : 您可以使用IntStream生成索引,然后filter以获取过滤的索引和mapToObj以获取相应的对象:

List<Object> newlist =
    IntStream.range(0,objectList.size())
             .filter(i -> booleanList.get(i))
             .mapToObj(i -> objectList.get(i))
             .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM