3

I have a method to validate no negative numbers in List of numbers:

private void validateNoNegatives(List<String> numbers) {
    List<String> negatives = numbers.stream().filter(x->x.startsWith("-")).collect(Collectors.toList());
    if (!negatives.isEmpty()) {
        throw new RuntimeException("negative values found " + negatives);
    }
}

Is it possible to use a method reference instead of x->x.startsWith("-")? I thought about String::startsWith("-") but is not working.

2
  • I doubt it is possible to get an "applied" method reference, but you could create the lambda prior and merely supply it as an argument. Commented Jul 22, 2014 at 12:20
  • 1
    Not the question you asked, but you could do this test more simply using noneMatch. For example, numbers.stream().noneMatch(x -> x.startsWith("-")); Commented Jul 22, 2014 at 15:48

1 Answer 1

8

No, you can't use a method reference because you need to provide an argument, and because the startsWith method doesn't accept the value you're trying to predicate. You could write your own method, as:

private static boolean startsWithDash(String text) {
    return text.startsWith("-");
}

... then use:

.filter(MyType::startsWithDash)

Or as a non-static method, you could have:

public class StartsWithPredicate {
    private final String prefix;

    public StartsWithPredicate(String prefix) {
        this.prefix = prefix;
    }

    public boolean matches(String text) {
        return text.startsWith(text);
    }
}

Then use:

// Possibly as a static final field...
StartsWithPredicate predicate = new StartsWithPredicate("-");
// Then...
List<String> negatives = numbers.stream().filter(predicate::matches)...

But then you might as well make StartsWithPredicate implement Predicate<String> and just pass the predicate itself in :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.