从数据集合中深层次条件遍历元素

Selector

在开发过程中,经常会遇到一个问题,就是列表或者数组中的元素,要按照其对象的某个变量去遍历数据。每次遇到这种情况,都要写一个循环来处理。为了减少这种操作,个人写了一个非常简单的库来减少这种操作。
代码已在Github开源Selector. 该库是为了帮助并改进我的另外一个开源库DelegateAdapter所写的,故依附在DelegateAdapter项目下。也可以单独拿出来使用。在android项目中的引用方式如下:

安装

compile 'com.github.boybeak:selector:0.2.0'

使用

示例对象类如下:

public class User {

    private int avatar;
    private String name;
    private String description;

    public User (int avatar, String name, String description) {
        this.avatar = avatar;
        this.name = name;
        this.description = description;
    }

    public int getAvatar() {
        return avatar;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public void setAvatar(int avatar) {
        this.avatar = avatar;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

有一个列表或者数组中,包含若干User对象,这里暂且以列表为例.
我们要从这个列表中获取名字长度大于5的用户数量,可以这样做

//get count of user.getName.length > 5
int count = Selector.selector(User.class, list)
                .where(Path.with(User.class, Integer.class).methodWith("getName.length"), Operator.OPERATOR_GT, 5)
                .count();

获取所有名字长度大于5的用户可以如下操作

//get all user of user.getName.length > 5
List<User> userList = Selector.selector(User.class, list)
                .where(Path.with(User.class, Integer.class).methodWith("getName.length"), Operator.OPERATOR_GT, 5)
                .findAll();

获取所有名字大于5的用户的名字,可以这样写

//get all user.name of user.getName.length > 5
List<String> nameList = Selector.selector(User.class, list)
                .where(Path.with(User.class, Integer.class).methodWith("getName.length"), Operator.OPERATOR_GT, 5)
                .extractAll(Path.with(User.class, String.class).methodWith("getName"));

遍历所有符合条件的对象

Selector.selector(User.class, list).where(Path.with(User.class, Integer.class).methodWith("getName").methodWith("length"), Operator.OPERATOR_GT, 5).map(new Action<User>() {
            @Override
            public void action(int index, User user) {
                user.setDescription("This is a name length > 5 user");
            }
        });

通过extractAll来提取对象中的元素集合。

多条件

在where后,可以跟and, or, xor三个方法,来连接多个条件查询或者遍历,比如:

Selector.selector(User.class, list).where(Path.with(User.class, Integer.class).methodWith("getName").methodWith("length"), Operator.OPERATOR_GT, 5)
                .and(Path.with(User.class, String.class).methodWith("getAvatar"), Operator.OPERATOR_IS_NULL).map(new Action<User>() {
            @Override
            public void action(int index, User user) {
                user.setDescription("This is a name length > 5 and null avatar user");
            }
        });

目前这个库还在探索阶段,希望多多鼓励与意见。

猜你喜欢

转载自blog.csdn.net/boybeak/article/details/73656610