Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case Insensitive filtering using Google Guava

Tags:

guava

Current I am using following piece of code to create a filter, in a map to match and give a filtered list of resultset.

final Map filteredMap = Maps.filterKeys(mymap, Predicates.containsPattern("^Xyz"));

However Guava Predicates.containsPattern does case-sensitive matching.

How should I use containsPattern for doing case-Insensitive matching.

like image 634
Anand Sanghvi Avatar asked Dec 07 '25 10:12

Anand Sanghvi


1 Answers

Use

Predicates.contains(Pattern.compile("^Xyz", Pattern.CASE_INSENSITIVE))

as predicate instead. See core Java Pattern and Predicates.contains.

EDIT (after OP's comment): yes, you can write:

Predicates.containsPattern("(?i)^Xyz"))

(see Pattern's documentation: Case-insensitive matching can also be enabled via the embedded flag expression (?i).) but it's IMO less self-explaining, plus compiled Pattern from first example can be cached to some private static final constant when used in a loop, which can improve performance.

like image 180
Xaerxess Avatar answered Dec 10 '25 00:12

Xaerxess



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!