xman
xman

Reputation: 11

What is the "->" operator in Java? Is it even an operator?

I saw this bit of code on Oracle's java documentation page for java.util.stream

int sum = widgets.stream()
                  .filter(b -> b.getColor() == RED)
                  .mapToInt(b -> b.getWeight())
                  .sum();

My question - what does "b -> b.getColor()" mean? What is the -> operator?

Upvotes: 0

Views: 177

Answers (1)

Keppil
Keppil

Reputation: 46219

The -> is part of a lambda expression. These were introduced in Java 8, and you can read more about them in The Java Tutorials. In short, a lambda expression can replace an anonymous class if you are implementing an interface that contains only one method.

Also, the syntax of the lambda expression is described in detail in the JLS §15.27:

A lambda expression is like a method: it provides a list of formal parameters and a body - an expression or block - expressed in terms of those parameters.
LambdaExpression:
LambdaParameters -> LambdaBody

Examples:  
() -> {}                // No parameters; result is void  
() -> 42                // No parameters, expression body
() -> {                 // Complex block body with returns
  if (true) return 12;
  else {
    int result = 15;
    for (int i = 1; i < 10; i++)
      result *= i;
    return result;
  }
} 
(int x) -> x+1          // Single declared-type parameter

Upvotes: 5

Related Questions