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()
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With