Java – filter the object only if the predicate input is not an empty string using guava
•
Java
I'm learning guava now. I have a problem I have three possible string filters The problem is that I just want to filter the collection of objects when the string is not "" (empty string) My other problem is how to filter different members from objects, such as object getName()== firstStringFilter. I would appreciate it if someone knew how to do it
solution
This is what I finally did with my code If my firststring filter is not empty, it is applied and is the same as the other two string filters I'm using the same list and overwriting it with the results of the filter
List<Field> fieldList = mLand.getFields(); if(!filterPattern.equalsIgnoreCase("")) { Predicate predicate = new Predicate<Field>() { @Override public boolean apply(Field input) { return input.getName() .toLowerCase() .contains(filterPattern); } }; Collection<Field> result = Collections2.filter(fieldList,predicate); fieldList = new ArrayList<>(result); } if(!cropStringPattern.equalsIgnoreCase("")) { Predicate predicate = new Predicate<Field>() { @Override public boolean apply(Field input) { return input.getCrop().getName() .toLowerCase() .contains(cropStringPattern); } }; Collection<Field> result = Collections2.filter(fieldList,predicate); fieldList = new ArrayList<>(result); } if(!varietyStringPattern.equalsIgnoreCase("")) { Predicate predicate = new Predicate<Field>() { @Override public boolean apply(Field input) { return input.getCrop().getVariety().getName() .toLowerCase() .contains(varietyStringPattern); } }; Collection<Field> result = Collections2.filter(fieldList,predicate); fieldList = new ArrayList<>(result); }
Solution
It doesn't sound like your objects are strings, but they have a string attribute, so it's like
Iterables.filter(objects,new Predicate<MyObject>() { @Override public boolean apply(MyObject object) { return !object.getName().isEmpty(); // or whatever condition here } });
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码