gpt4 book ai didi

java - 使用对象的字段过滤 ArrayList

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:02 24 4
gpt4 key购买 nike

我有一个由对象填充的 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/57553458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com