如何有选择地过滤集合中的项目 [英] how to selectively filter items in a collection

查看:89
本文介绍了如何有选择地过滤集合中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码段过滤所选用户的列表,其中isSelected是一个布尔变量。有一个更简单的方法(帮助函数)填充selectedUsers集合,而不是编写以下代码行。

  List< User> ; selectedUsers = new ArrayList< User>(0); 
for(User user:this.getUsers()){
if(user.isSelected()){
selectedUsers.add(user.getId());
}
}


解决方案

可以使用过滤器函数从Google Collections;然而,你仍然需要构造一个谓词对象,如果你想操作结果,你将不得不构造另一个集合并传递结果,因为过滤器的结果是原始集合的不可变的过滤视图。 / p>

更具体的:

 列表< User> selectedUsers = new ArrayList< User>(
Iterables.filter(
this.getUsers(),
new Predicate< User>()
{
public boolean apply user usr){
return usr.isSelected();
}
}
));

当然,这不是真的那么干净(除非你为你的谓词做一个单独的类,碰巧在一堆地方重复使用它),它实际上返回用户列表,而不是他们的ID ...你必须使用转换来获取他们的ID,所以亲自,我只是去与你的现在。


I use the following snippet to filter the list of selected users, where isSelected is a boolean variable. Is there a simpler way (helper function) to populate the selectedUsers collection instead of writing the following lines of code.

List<User> selectedUsers = new ArrayList<User>(0);
for (User user : this.getUsers()) {
    if (user.isSelected()) {
        selectedUsers.add(user.getId());
    }
}

解决方案

You can use the filter function from the Google Collections; however, you will still need to construct a predicate object, and if you want to manipulate the result, you will have to construct another collection and pass the result in, since the result of filter is an immutable filtered view of the original collection.

To make this more concrete:

List<User> selectedUsers = new ArrayList<User>(
           Iterables.filter(
                  this.getUsers(),
                  new Predicate<User>()
                      {
                          public boolean apply(User usr){ 
                                return usr.isSelected();
                          }
                       }
           ));

Of course, this is not really that much cleaner (unless you make a separate class for your predicate and happen to reuse it in a bunch of places), and it actually returns the list of users, not their IDs... you would have to use a "transform" to get their IDs, so personally, I would just go with what you have now.

这篇关于如何有选择地过滤集合中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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