Trainee Coder
Trainee Coder

Reputation: 33

How to create something equivalent to the following logic using java8 streams?

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;
}

Upvotes: 1

Views: 71

Answers (2)

Remo
Remo

Reputation: 604

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);
    }

Upvotes: 1

ETO
ETO

Reputation: 7279

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);
}

Upvotes: 1

Related Questions