[英]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.