根据另一个列表从列表中过滤元素 [英] Filter Elements from a list based on another list

查看:745
本文介绍了根据另一个列表从列表中过滤元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆