[英]CollectionUtils in java using predicate
I have a List<Object>
and I want to return the first value that it finds true which matches a predicate. 我有一个
List<Object>
,我想返回它找到的第一个与谓词匹配的值。
I found that I can use CollectionUtils.find(collection,predicate)
(Apache commons). 我发现我可以使用
CollectionUtils.find(collection,predicate)
(Apache commons)。 Assuming that the Object
contains a integer variable called : value
, how do i specify in the predicate that the value can be 1,2,3,4,5
and to discard those that dont match. 假设
Object
包含一个名为: value
的整数变量,我如何在谓词中指定该值可以是1,2,3,4,5
并丢弃那些不匹配的值。 Is it possible to do 'contains'. 有可能做'包含'。
Also not using java 8 so unable to do stream. 也没有使用java 8所以无法做流。
To return the first element in the list which matches the given predicate: 要返回列表中与给定谓词匹配的第一个元素:
MyObject res = CollectionUtils.find(myList, new Predicate<MyObject>() {
@Override
public boolean evaluate(MyObject o) {
return o.getValue() >= 1 && o.getValue() <= 5;
}
});
To filter the list so that it only contains elements matching the predicate: 要过滤列表,使其仅包含与谓词匹配的元素:
CollectionUtils.filter(myList, new Predicate<MyObject>() {
@Override
public boolean evaluate(MyObject o) {
return o.getValue() >= 1 && o.getValue() <= 5;
}
});
You can notice that the Predicate<MyObject>
is the same. 您可以注意到
Predicate<MyObject>
是相同的。
In Java 8 you can write 在Java 8中,您可以编写
Optional<Integer> found = list.stream().filter(i -> i >= 1 && i <= 5).findAny();
Before Java 7 the simplest solution is to use a loop. 在Java 7之前,最简单的解决方案是使用循环。
Integer found = null;
for(integer i : list)
if (i >= 1 && i <= 5) {
found = i;
break;
}
This would be the cleanest and fastest way as Java 7 doesn't have support for lambdas. 这将是最简洁,最快速的方式,因为Java 7不支持lambdas。
You can use Collections.removeIf (I'm assuming you are using JDK 8). 您可以使用Collections.removeIf (我假设您使用的是JDK 8)。 You can also use a Stream :
您还可以使用Stream:
list = list.stream().filter(predicate).collect(Collectors.toList());
Using Apach Commons Collections, you can use CollectionUtils.filter . 使用Apach Commons Collections,您可以使用CollectionUtils.filter 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.