Mah*_*leh 12 java collections apache-commons
我有一个项目列表,我想找到一个具有布尔属性(字段变量)的项目列表x=true
.
我知道这可以通过迭代来完成,但我一直在寻找一种在Apache Commons这样的公共库中执行此操作的常用方法.
Fra*_*eth 21
您可以使用apache commons集合为它实现谓词.
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/CollectionUtils.html
样品:
package snippet;
import java.util.Arrays;
import java.util.Collection;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
public class TestCollection {
public static class User {
private String name;
public User(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [name=" + name + "]";
}
}
public static void main(String[] args) {
Collection<User> users = Arrays.asList(new User("User Name 1"), new User("User Name 2"), new User("Another User"));
Predicate predicate = new Predicate() {
public boolean evaluate(Object object) {
return ((User) object).getName().startsWith("User");
}
};
Collection filtered = CollectionUtils.select(users, predicate);
System.out.println(filtered);
}
}
Run Code Online (Sandbox Code Playgroud)
可在此处找到一些示例:http: //apachecommonstipsandtricks.blogspot.de/2009/01/examples-of-functors-transformers.html
如果您需要更通用的内容,例如检查特定字段或属性的值,您可以执行以下操作:
public static class MyPredicate implements Predicate {
private Object expected;
private String propertyName;
public MyPredicate(String propertyName, Object expected) {
super();
this.propertyName = propertyName;
this.expected = expected;
}
public boolean evaluate(Object object) {
try {
return expected.equals(PropertyUtils.getProperty(object, propertyName));
} catch (Exception e) {
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这可以将特定属性与预期值进行比较,并且使用类似于:
Collection filtered = CollectionUtils.select(users, new MyPredicate("name", "User Name 2"));
Run Code Online (Sandbox Code Playgroud)
Pet*_*rey 11
问题是Java中的迭代通常更简单,更清晰.也许Java 8的Closures将解决这个问题.;)
与@ Spaeth的解决方案比较.
List<String> mixedup = Arrays.asList("A", "0", "B", "C", "1", "D", "F", "3");
List<String> numbersOnlyList = new ArrayList<>();
for (String s : mixedup) {
try {
// here you could evaluate you property or field
Integer.valueOf(s);
numbersOnlyList.add(s);
} catch (NumberFormatException ignored) {
}
}
System.out.println("Results of the iterated List: " + numbersOnlyList);
Run Code Online (Sandbox Code Playgroud)
你可以看到它更短更简洁.
List<Foo> result = foos.stream()
.filter(el -> el.x == true)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
https://www.mkyong.com/java8/java-8-streams-filter-examples/