I have an ArrayList which is filled by Objects.
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;}
}
I want to filter my List using the desArt
field, and for test I used the String "test".
I used the Guava from google which allows me to filter an ArrayList.
this is the code I tried :
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")));
but this code isn't working.
This is normal: Predicates.containsPattern() operates on
CharSequence
s, which yourgestionStock.Article
object does not implement.You need to write your own predicate:
Then use:
However, this is quite some code for something which can be done in much less code using non functional programming, as demonstrated by @mgnyp...
With Guava, I would say that the easiest way by far would be by using Collections2.filter, such as:
In Java 8, using filter
Try this:
The idea being is since you're using a custom object, you should implement your own predicate. If you're using it anywhere else, define it in a file, otherwise, this implementation works nicely.
Guava is a library that allows you to use some functional programming in Java. One of the winning things in functional programming is collection transformation like
Collection -> op -> op -> op -> transformedCollection.
Look here:
It's beautiful, isn't it?
The second one winning thing is lambda functions. Look here:
Actually, Java has not pure lambda functions yet. We will be able to do it in Java 8. But for now we can write this in IDE Inellij Idea, and IDE transforms such lambda into Predicate, created on-the-fly:
If your filter condition requires regexp, the code become more complicated, and you will need to move condition to separate method or move whole Predicate to a separate class.
If all this functional programming seems too complicated, just create new collection and fill it manually (without Guava):
You can use a for loop or for each loop to loop thru the list. Do you want to create another list based on some condition? This should work I think.