根据另一个列表从列表中过滤元素 [英] Filter Elements from a list based on another list
问题描述
我想在 Java 8
我有布尔
列表和另一个对象
列表,这两个列表的大小始终相同。我想删除 object
列表中的所有元素,它们在 false
> boolean list。
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};
所以从这些列表中,我想更改 objectList
来
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`.
如果我在 Java 7中执行此操作
,我会做以下事情:
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;
有没有办法在 Java 8中执行此操作
代码较小?
Is there a way to do this in Java 8
with lesser code?
推荐答案
您可以使用 IntStream
来生成索引,然后过滤器
获取过滤后的索引, mapToObj
获取相应的对象:
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());
这篇关于根据另一个列表从列表中过滤元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!