Search code examples
guava

Case Insensitive filtering using Google 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.


Solution

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