Java
Programming
Arrow Operator
Coding
Java Syntax

What does the arrow operator (->) do in Java?

Codemia Knowledge Hub ·

The arrow operator (->) in Java separates the parameter list from the body in lambda expressions and switch expressions. It arrived with lambdas in Java 8 and was extended to switch in Java 14, and it is the core syntax behind functional-style Java.

-> in lambda expressions

A lambda expression is an anonymous function that implements a functional interface (an interface with exactly one abstract method). The parameters go on the left of the arrow and the implementation on the right:

java
1// Syntax: (parameters) -> expression_or_block
2
3// No parameters
4Runnable task = () -> System.out.println("Running");
5
6// Single parameter (parentheses optional)
7Consumer<String> printer = s -> System.out.println(s);
8
9// Multiple parameters
10BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
11
12// Block body with return
13Comparator<String> byLength = (s1, s2) -> {
14    int diff = s1.length() - s2.length();
15    return diff;
16};

The compiler infers parameter types from the target functional interface, so you rarely need to write them.

Replacing anonymous classes

Before Java 8, implementing a functional interface required an anonymous inner class. A lambda removes that boilerplate with identical behavior:

java
1// Before Java 8: anonymous inner class
2Collections.sort(names, new Comparator<String>() {
3    @Override
4    public int compare(String a, String b) {
5        return a.compareToIgnoreCase(b);
6    }
7});
8
9// Java 8+: lambda with arrow operator
10Collections.sort(names, (a, b) -> a.compareToIgnoreCase(b));
11
12// Even shorter with method reference
13Collections.sort(names, String::compareToIgnoreCase);

Lambdas in stream pipelines

The arrow operator is used heavily with the Streams API, where each lambda is invoked for every element:

java
1List<String> names = List.of("Alice", "Bob", "Charlie", "Diana", "Eve");
2
3// Filter, transform, and collect in a pipeline
4List<String> result = names.stream()
5    .filter(name -> name.length() > 3)        // Predicate<String>
6    .map(name -> name.toUpperCase())           // Function<String, String>
7    .sorted((a, b) -> a.compareTo(b))          // Comparator<String>
8    .collect(Collectors.toList());
9// result: ["ALICE", "CHARLIE", "DIANA"]

Standard functional interfaces

java.util.function provides the interfaces lambdas usually target:

InterfaceMethod SignatureLambda Example
Predicate<T>boolean test(T t)x -> x > 10
Function<T, R>R apply(T t)s -> s.length()
Consumer<T>void accept(T t)s -> System.out.println(s)
Supplier<T>T get()() -> new ArrayList<>()
BiFunction<T, U, R>R apply(T t, U u)(a, b) -> a + b
UnaryOperator<T>T apply(T t)x -> x * 2
BinaryOperator<T>T apply(T t1, T t2)(a, b) -> Math.max(a, b)

You only need your own functional interface if none of these fit.

-> in switch expressions (Java 14+)

Java 14 added a second use: case VALUE -> branches in switch expressions replace the traditional case: ... break; pattern:

java
1// Traditional switch (prone to fall-through bugs)
2String result;
3switch (day) {
4    case MONDAY:
5    case FRIDAY:
6        result = "Work hard";
7        break;
8    case SATURDAY:
9    case SUNDAY:
10        result = "Relax";
11        break;
12    default:
13        result = "Normal day";
14        break;
15}
16
17// Switch expression with arrow operator (Java 14+)
18String result = switch (day) {
19    case MONDAY, FRIDAY -> "Work hard";
20    case SATURDAY, SUNDAY -> "Relax";
21    default -> "Normal day";
22};

Arrow branches never fall through to the next case, which eliminates a whole class of bugs. When a branch needs several statements, use a block with yield:

java
1String result = switch (statusCode) {
2    case 200 -> "OK";
3    case 404 -> "Not Found";
4    case 500 -> {
5        logError(statusCode);
6        yield "Internal Server Error";
7    }
8    default -> "Unknown status";
9};

Captured variables must be effectively final

Lambdas can use variables from the enclosing scope only if they are never reassigned after initialization:

java
1String prefix = "Hello, ";  // effectively final
2
3// This works - prefix is never reassigned
4Function<String, String> greeter = name -> prefix + name;
5
6// This would NOT compile:
7// prefix = "Hi, ";  // reassignment makes it non-effectively-final

The lambda may run later or on a different thread, and allowing mutation would introduce race conditions.

Method references (::) as shorthand

When a lambda just calls an existing method, a method reference can replace it:

java
1// Lambda with arrow operator
2names.forEach(name -> System.out.println(name));
3
4// Equivalent method reference (no arrow needed)
5names.forEach(System.out::println);
6
7// Static method reference
8numbers.stream().map(n -> String.valueOf(n));
9numbers.stream().map(String::valueOf);
10
11// Instance method reference
12names.stream().map(s -> s.toUpperCase());
13names.stream().map(String::toUpperCase);

Method references do not replace -> in general. They are sugar for the specific case where the body is a single method call that forwards all parameters directly.

Lambda mistakes to avoid

Returning a value in a void context. If the interface method returns void, an expression body that produces a value is allowed but can be confusing. Use a block body if the intent is unclear.

Missing return in a block body. An expression body (x -> x + 1) returns its result implicitly. A block body (x -> { x + 1; }) does not; write x -> { return x + 1; }.

Mixing up -> and ::. Use -> for custom logic and :: only when the body is a direct method delegation.

Long nested chains. Chains of more than 3 or 4 operations get hard to read. Extract complex lambdas into named methods and use method references.

Shadowing outer variables. A lambda parameter cannot share a name with a variable in the enclosing scope. Unlike anonymous classes, which create a new scope, this is a compilation error:

java
String name = "outer";
// Compilation error: variable 'name' is already defined
Consumer<String> c = name -> System.out.println(name);

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms