简体   繁体   中英

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.

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'.

Also not using java 8 so unable to do stream.

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.

In Java 8 you can write

Optional<Integer> found = list.stream().filter(i -> i >= 1 && i <= 5).findAny();

Before Java 7 the simplest solution is to use a loop.

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.

You can use Collections.removeIf (I'm assuming you are using JDK 8). You can also use a Stream :

list = list.stream().filter(predicate).collect(Collectors.toList());

Using Apach Commons Collections, you can use CollectionUtils.filter .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM