Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 286
Rory Lester Avatar asked Sep 01 '14 13:09

Rory Lester


People also ask

How do you use CollectionUtils in Java?

MyObject res = CollectionUtils. find(myList, new Predicate<MyObject>() { @Override public boolean evaluate(MyObject o) { return o. getValue() >= 1 && o. getValue() <= 5; } });

What is Java CollectionUtils?

Simply put, the Apache CollectionUtils provides utility methods for common operations which cover a wide range of use cases and helps in avoiding writing boilerplate code. The library targets older JVM releases because currently, similar functionality is provided by the Java 8's Stream API.

What does CollectionUtils isEmpty do?

isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.


1 Answers

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.

like image 80
Jean Logeart Avatar answered Sep 19 '22 10:09

Jean Logeart