Вопрос

Sorry for the simple question - I come from the .NET stack. All I want is an inline Predicate. Please tell me what I'm doing wrong:

toReturn = Iterables.find(articles, a -> a.toString().equals(input));

It tells me that 'a cannot be resolved to a variable'. I'm assuming that I just need an import or that I'm using an old version of Java? Thanks in advance!

Это было полезно?

Решение

What you're trying to do is not possible in Java 7 or earlier; it exists in Java 8 and later though. With Java 7 and prior you are able to use lambdaj to similar effect though. It would look something like this:

toReturn = Iterables.find(articles, new Predicate<Object>() {
    public boolean apply(Object item) {
            return item.toString().equals(input);
    }
});

You can check out more details here.

Edit: As pointed out in the comments, there are alternatives. As you're using Iterables I'm guessing you would want a com.google.common.base.Predicate which can be defined very similarly:

toReturn = Iterables.find(articles, new Predicate<Object>() {
    public boolean apply(Object item) {
            return item.toString().equals(input);
    }

    public boolean equals(Object obj) {
        // check whether the other object is also a Predicate
    }
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top