oshai
oshai

Reputation: 15365

Reference a method (for use in a lambda) with specified parameters

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.

Upvotes: 3

Views: 910

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500515

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 :)

Upvotes: 8

Related Questions