使用对象的字段过滤 ArrayList [英] filtering an ArrayList using an object's field

查看:32
本文介绍了使用对象的字段过滤 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由对象填充的 ArrayList.

I have an ArrayList which is filled by Objects.

我的对象类叫做Article,它有两个字段;

My object class called Article which has two fields ;

public class Article {

    private int codeArt;
    private String desArt;

  public Article(int aInt, String string) {
        this.desArt = string;
        this.codeArt = aInt;
    }

    public int getCodeArt() {return codeArt; }
    public void setCodeArt(int codeArt) {this.codeArt = codeArt;}
    public String getDesArt() {return desArt;}
    public void setDesArt(String desArt) { this.desArt = desArt;}

}

我想使用 desArt 字段过滤我的列表,并且为了测试,我使用了字符串test".

I want to filter my List using the desArt field, and for test I used the String "test".

我使用了谷歌的番石榴,它允许我过滤一个 ArrayList.

I used the Guava from google which allows me to filter an ArrayList.

这是我试过的代码:

private List<gestionstock.Article> listArticles = new ArrayList<>();

//Here the I've filled my ArrayList

private List<gestionstock.Article> filteredList filteredList = Lists.newArrayList(Collections2.filter(listArticles, Predicates.containsPattern("test")));

但是此代码不起作用.

推荐答案

这是正常的:Predicates.containsPattern()CharSequence 进行操作,您的 gestionStock.Article对象没有实现.

This is normal: Predicates.containsPattern() operates on CharSequences, which your gestionStock.Article object does not implement.

您需要编写自己的谓词:

You need to write your own predicate:

public final class ArticleFilter
    implements Predicate<gestionstock.Article>
{
    private final Pattern pattern;

    public ArticleFilter(final String regex)
    {
        pattern = Pattern.compile(regex);
    }

    @Override
    public boolean apply(final gestionstock.Article input)
    {
        return pattern.matcher(input.getDesArt()).find();
    }
}

然后使用:

 private List<gestionstock.Article> filteredList
     = Lists.newArrayList(Collections2.filter(listArticles,     
         new ArticleFilter("test")));

然而,正如@mgnyp 所展示的那样,这是一些可以使用非函数式编程以更少的代码完成的代码......

However, this is quite some code for something which can be done in much less code using non functional programming, as demonstrated by @mgnyp...

这篇关于使用对象的字段过滤 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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