Search code examples
javalistsearchjava-streamcase-insensitive

Performing a case in-sensitive search on a java List using stream().filter()


I'm trying to perform an case in-sensitive search on a Java List using stream().filter(...).

My search function works fine but i haven't managed to implement this to work without case sensitivity. My function looks something like this:

public static List<License> searchByEverything(String keyword, String dealerid){
    List<License> licenseDealerList = getLicensesByDealer(dealerid);

   // org.apache.commons.lang3.StringUtils.containsIgnoreCase(keyword);


    Predicate<License> licensePredicate = u -> u.name1.contains(keyword);
    List<License> filteredList = licenseDealerList.stream().filter(licensePredicate).collect(Collectors.toList());

    return filteredList;
}

As you can see i tried to use the apache commons library but i don't get it how to include it in my stream().filter(...). I researched some different methods but didn't really understand how to implement any of them into my method. In my case it's really important that the search is performed from a string value on the object values and that it returns an object.

I know i could use something like matchAny() instead of filter() but i didn't understand how to return it as an object.

Thanks in advance


Solution

  • You could use toLowerCase():

    u -> u.name1.toLowerCase().contains(keyword.toLowerCase());
    

    This way both values are in the same case and your search is case in-sensitive.