1

I wish to create a method equivalent to the following using Java 8 streams but not able to do this. Can someone guide me here?

public boolean checkCondition(List<String> ruleValues, List<String> inputValues) {
    boolean matchFound = false;
    for (String ruleValue : ruleValues) {
        for (String inputValue : inputValues) {
            if (ruleValue.equalsIgnoreCase(inputValue)) {
                matchFound = true;
                break;
            }
        }
    }
    return matchFound;
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 2
    `return ruleValues.stream().anyMatch(ruleValue -> inputValues.stream().anyMatch(ruleValue::equalsIgnoreCase));` – Lino Feb 17 '22 at 09:46
  • Related question: https://stackoverflow.com/q/11796371/5515060 – Lino Feb 17 '22 at 12:54

2 Answers2

1

Try this approach. It will run in O(n) time:

public boolean checkCondition(List<String> ruleValues, List<String> inputValues) {
    Set<String> rules = ruleValues.stream()
                                  .map(String::toLowerCase)
                                  .collect(toSet());

    return inputValues.stream()
                      .map(String::toLowerCase)
                      .anyMatch(rules::contains);
}
ETO
  • 6,970
  • 1
  • 20
  • 37
1

Equivalent Java 8 code:

    public boolean checkCondition(final List<String> ruleValues, final List<String> inputValues) {

        final Predicate<String> checkRuleValue = ruleValue -> inputValues
            .stream()
            .anyMatch(ruleValue::equalsIgnoreCase);

        return ruleValues
            .stream()
            .anyMatch(checkRuleValue);
    }
Remo
  • 534
  • 7
  • 26