Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add Predicate into List

Is there any way to dynamically add Predicate into List in Java? For a brief illustration I've done it like this:

List<Predicate<String>> filters = Arrays.asList(
    t -> !Utilities.isNumeric(t)
);
filters.add(t -> !t.isEmpty());

But executing the filters.add results in UnsupportedOperationException. Fixed List like this is fine tho.

List<Predicate<String>> filters = Arrays.asList(
    t -> !Utilities.isNumeric(t),
    t -> !t.isEmpty()
);
like image 686
Habib Rosyad Avatar asked Oct 23 '25 03:10

Habib Rosyad


1 Answers

Solution:

List<Predicate<String>> filters = new ArrayList<>(Arrays.asList(
    t -> !Utilities.isNumeric(t)
));

Explanation:

Arrays.asList returns a fixed-length list1 wrapper for the array argument. Since it is fixed sized, methods that would change the size throw UnsupportedOperationException.

By feeding this to the ArrayList constructor, you create a new list, whose size can be changed.


1 - .... but the list is NOT immutable. It can be modified by updating the backing array, or by using the List::set(int, T) method.

like image 104
Stephen C Avatar answered Oct 24 '25 17:10

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!