Close

Java - How to find if a string contains all or any of the given strings while ignoring case?

[Last Updated: May 18, 2018]

Java String Manipulation Java 



Following code shows how to find if a string contains all or any of the provided strings while ignoring the cases.

package com.logicbig.example;

import java.util.Arrays;

public class ContainsAnyOrAll {

  public static boolean containsAny(String str, boolean ignoreCase, String... parts) {
      if (str == null || parts == null || parts.length == 0) {
          return false;
      }
      if (ignoreCase) {
          str = str.toLowerCase();
      }
      String finalStr = str;
      return Arrays.stream(parts)
                   .filter(s -> s != null && s.length() > 0)
                   .map(s -> ignoreCase ? s.toLowerCase() : s)
                   .anyMatch(s -> finalStr.contains(s));
  }

  public static boolean containsAll(String str, boolean ignoreCase, String... parts) {
      if (str == null || parts == null || parts.length == 0) {
          return false;
      }
      if (ignoreCase) {
          str = str.toLowerCase();
      }
      String finalStr = str;
      return Arrays.stream(parts)
                   .allMatch(s -> {//allMatch returns true if stream is empty so we cannot use filter()
                       if (s == null || s.length() == 0) {
                           return false;
                       }
                       if (ignoreCase) {s = s.toLowerCase();}
                       return finalStr.contains(s);
                   });
  }

  public static void main(String[] args) {
      String input = "Cheese bread avocado banana";

      boolean b = containsAny(input, true, "Banana");
      System.out.println(b);

      b = containsAny(input, true, "Beer", "Avocado");
      System.out.println(b);

      b = containsAll(input, true, "Beer", "Avocado");
      System.out.println(b);

      b = containsAll(input, true, "Banana", "Avocado");
      System.out.println(b);

      b = containsAny(input, true, "");
      System.out.println(b);

      b = containsAny(input, true, null, null);
      System.out.println(b);
  }
}
true
true
false
true
false
false

See Also