我有一个由对象填充的 ArrayList。
我的对象类 Article
有两个字段;
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”。
我使用了 google 的 Guava,它允许我过滤 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")));
但是这段代码不起作用。
最佳答案
在 Java 8 中,使用过滤器
List<Article> articleList = new ArrayList<Article>();
List<Article> filteredArticleList= articleList.stream().filter(article -> article.getDesArt().contains("test")).collect(Collectors.toList());
关于java - 使用对象的字段过滤 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16856554/