java中的CollectionUtils使用谓词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25606563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CollectionUtils in java using predicate
提问by Rory Lester
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). 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. Is it possible to do 'contains'.
我发现我可以使用CollectionUtils.find(collection,predicate)
(Apache commons)。假设Object
包含一个名为 : 的整数变量value
,我如何在谓词中指定该值可以是1,2,3,4,5
并丢弃那些不匹配的值。是否可以执行“包含”。
Also not using java 8 so unable to do stream.
也没有使用 java 8 所以无法做流。
采纳答案by Jean Logeart
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>
是一样的。
回答by Dici
You can use Collections.removeIf(I'm assuming you are using JDK 8). You can also use a Stream :
您可以使用Collections.removeIf(我假设您使用的是 JDK 8)。您还可以使用 Stream :
list = list.stream().filter(predicate).collect(Collectors.toList());
Using Apach Commons Collections, you can use CollectionUtils.filter.
使用 Apache Commons Collections,您可以使用CollectionUtils.filter。
回答by Peter Lawrey
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。