Geek Stocks Geek Stocks - 4 months ago 10
Java Question

What is '->' in Java 8?

I am learning Predicates in Java 8. I expected to find that '->' was simply an operator that I was unfamiliar with. However, upon searching the docs and other tutorial sites I can find no mention of '->' even being an operator.

public Predicate<String> verbMatches(String _verb) {
return t -> t.equalsIgnoreCase(_verb);
}


My questions are:


  1. Is it an operator? If not what is it?

  2. In the code above, what is it doing?

  3. Why does it work with a generic that hasn't been defined?


Answer

It is a Lambda expression, with which you can write shorter code:

int i1 = calcInt(2, 5, new IntOperator() {
    @Override
    public int apply(int i, int j) {
         return i + j;
    }
});

becomes

int i1 = calcInt(2, 5, (i, j) -> i + j); // i1 == 7 

for example. You can finde more detailed information in the Java Doc - Lambda Expressions

Comments