Code Quality: Clean Code in Java ·
‹ Previous Next ›
⏱ 7 min read Modified: 2026-12-05

Code Smells in Java: Lambdas, Streams, Optional and Classic Smells

What does this code print? The pipeline has a peek() that should log every element:

long count = Stream.of("one", "two", "three", "four")
        .peek(s -> System.out.println("Visited: " + s))
        .count();
System.out.println("count = " + count);

long longWords = Stream.of("one", "two", "three", "four")
        .filter(s -> s.length() > 3)
        .peek(s -> System.out.println("Visited: " + s))
        .count();
System.out.println("longWords = " + longWords);
count = 4
Visited: three
Visited: four
longWords = 2

In the first pipeline nothing is logged. Since Java 9, count() may compute the size of the stream directly from the source and skip the pipeline, and the API documentation allows exactly that. Code that relies on a side effect inside a stream depends on optimizations it does not control — one of the code smells covered in this lesson.

A code smell is a surface sign in the code that usually points to a deeper design problem: a magic number, a duplicated block, a condition that is hard to read, a lambda twenty lines long. A smell is not a bug — the code works — but it makes the next change slower and riskier. This lesson collects the smells that appear most often in modern Java, from lambdas, streams and Optional to classic ones such as magic numbers and hidden temporal coupling.

Short lambdas and method references

A lambda should be an expression, ideally one line. When a lambda body grows into a block with several statements, move it into a named private method and refer to that method: the pipeline stays readable and the logic gets a name and a place to be tested.

List<String> labels = products.stream()
        .map(product -> {
            String name = product.name().strip();
            String price = String.format("%.2f", product.price());
            return name + " - " + price + " EUR";
        })
        .toList();

List<String> labels = products.stream()
        .map(this::toLabel)
        .toList();

private String toLabel(Product product) {
    return product.name().strip() + " - " + String.format("%.2f", product.price()) + " EUR";
}

Where a lambda only calls one existing method, a method reference is shorter and names the operation directly: map(String::length) instead of map(s -> s.length()), forEach(System.out::println) instead of forEach(x -> System.out.println(x)). Keep the lambda when the reference would be longer or less clear, for example when arguments have to be rearranged.

Readable streams: static imports, toList(), no peek()

A stream pipeline reads best with one operation per line, short lambdas and as little noise as possible around the operations. Three small habits help most.

Static imports for the usual stream helpers remove repetition without hiding anything a Java developer would not recognize:

import static java.util.Comparator.reverseOrder;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;

Map<String, Integer> lengths = words.stream()
        .sorted(reverseOrder())
        .limit(10)
        .collect(toMap(identity(), String::length));

Stream.toList() (Java 16) is the short form for collecting into a list, with one difference that matters: it returns an unmodifiable list, while collect(Collectors.toList()) returns a list whose mutability is not specified (in practice an ArrayList). Code that later calls add() on the result fails with UnsupportedOperationException after switching to toList(), so check the callers when you migrate. When you need a mutable list, say so explicitly with collect(Collectors.toCollection(ArrayList::new)).

Avoid peek() for logic. The JDK documentation says that the method exists mainly to support debugging. As the example at the top of the lesson shows, the stream is free to skip it, and it also runs lazily and possibly in parallel. Put side effects in forEach() or, better, outside the stream.

Standard functional interfaces

Before declaring your own functional interface, check java.util.function: Predicate, Function, Supplier, Consumer, UnaryOperator, BiFunction and their primitive versions cover most needs. Every Java developer knows them, and they come with useful default methods such as Predicate.and() and Function.andThen().

@FunctionalInterface
interface OrderFilter {            // reinvents Predicate<Order>
    boolean test(Order order);
}

Predicate<Order> isPaid = Order::paid;
Predicate<Order> isLarge = order -> order.total() > 1_000;
List<Order> toReview = orders.stream().filter(isPaid.and(isLarge)).toList();

A custom interface is still the right choice when the name carries domain meaning that a generic type would lose, or when the method must declare a checked exception. Annotate such interfaces with @FunctionalInterface so the compiler keeps them single-method. More in Functional Interface in Java.

Optional only as a return type

Optional was designed as a return type for methods that may have no result. Using it as a field, a method parameter or a collection element adds an allocation and a level of wrapping without making the code safer.

// Return type: the caller sees that the value may be missing
public Optional<Customer> findByEmail(String email) { /* ... */ }

Customer customer = repository.findByEmail(email)
        .orElseThrow(() -> new CustomerNotFoundException(email));

// Smells
private Optional<String> middleName;                 // field: use null internally or a default
void notify(Optional<String> phone) { /* ... */ }    // parameter: use an overload
List<Optional<Order>> orders;                         // element: just leave the empty ones out

Avoid the isPresent() + get() pair: it is a null check in disguise. Use orElseThrow(), orElse(), map() or ifPresent() instead, and never write Optional.of(value) for a value that can be null — that is what ofNullable() is for. The methods are compared in Optional Methods in Java.

DRY, KISS and least astonishment

Three general principles stand behind most specific smells. They are short to state and easy to forget under deadline pressure.

Principle Meaning Smell it prevents
DRY — Don’t Repeat Yourself Every piece of knowledge has one place in the code The same validation copied into three services, one copy forgotten in a fix
KISS — Keep It Simple Choose the simplest solution that solves today’s problem An abstract factory for a class with one implementation
Least astonishment Code behaves the way its name and context suggest A getTotal() that also saves to the database
Be consistent Similar things are named, formatted and structured the same way fetchUser(), getOrder() and loadInvoice() doing the same kind of work

DRY is about knowledge, not about text. Two blocks that look the same but change for different reasons are not duplication, and merging them creates coupling that hurts later.

Magic numbers and strings

A magic number is a literal whose meaning is not obvious from the code, such as 9.81 or 86400. Give it a name with a constant: the name explains the value, and a change happens in one place.

public class Physics {
    public static double potentialEnergy(double mass, double height) {
        return mass * height * 9.81;
    }

    public static double fallDistance(double seconds) {
        return 9.81 * seconds * seconds / 2;
    }
}

public class Physics {
    private static final double GRAVITY = 9.81; // m/s^2

    public static double potentialEnergy(double mass, double height) {
        return mass * height * GRAVITY;
    }

    public static double fallDistance(double seconds) {
        return GRAVITY * seconds * seconds / 2;
    }
}

For a fixed set of related values, an enum is better than a group of int or String constants: setStatus(OrderStatus.PAID) cannot receive 42, an enum can hold fields and methods, and a switch over it is checked by the compiler. See Enum in Java. Not every literal is magic: 0, 1 and -1 in obvious arithmetic, or / 2 in the formula above, read fine as they are.

Conditions that read like sentences

A complex condition should be wrapped in a method or a variable whose name states the rule, and it should be phrased positively. The reader then sees the decision instead of having to evaluate boolean logic.

if (timer.hasExpired() && !timer.isRecurrent()) { /* ... */ }
if (shouldBeDeleted(timer)) { /* ... */ }                // encapsulated condition

if (!buffer.shouldNotCompact()) { /* ... */ }
if (buffer.shouldCompact()) { /* ... */ }                // no double negative

Explanatory variables do the same for intermediate results. Compare headers.put(matcher.group(1).toLowerCase(), matcher.group(2)) with two lines that first name the parts:

if (matcher.find()) {
    String key = matcher.group(1);
    String value = matcher.group(2);
    headers.put(key.toLowerCase(), value);
}

Repeated switch statements

One switch on a type code is fine. The smell is the same switch repeated in several methods: every new case has to be added in every copy, and the one that is forgotten becomes a bug. Move the behavior into the type itself.

enum TrafficLight {
    RED {
        TrafficLight next() { return GREEN; }
    },
    GREEN {
        TrafficLight next() { return YELLOW; }
    },
    YELLOW {
        TrafficLight next() { return RED; }
    };

    abstract TrafficLight next();
}

Each constant now carries its own behavior, and a new light cannot be added without implementing next(). For hierarchies of records, a sealed interface with a pattern-matching switch gives a similar compile-time guarantee in a single place; when to prefer which is explained in the lesson on the open-closed principle.

Hidden temporal coupling

Hidden temporal coupling means that methods must be called in a particular order, but nothing in their signatures shows or enforces that order. Swap two lines and the code still compiles, then fails at runtime.

public void processOrder(String productName) {
    takeOrder();                      // sets the field order
    prepareProduct(productName);      // reads order, sets the field product
    sendProduct(productName);         // reads product
}

public void processOrder(String productName) {
    Order order = takeOrder(productName);
    Product product = prepareProduct(order);
    sendProduct(product);
}

In the second version each step returns what the next step needs, so the order is forced by the data: prepareProduct() cannot be called before there is an Order. The fields that only carried state between calls disappear too.

Dead code

Dead code is code that is never executed or no longer needed: unused imports, private methods nobody calls, variables that are assigned but never read, commented-out blocks, parameters that are ignored. It still has to be read, compiled and maintained, and it misleads readers into thinking it matters.

Delete it. Version control remembers it if it is ever needed again. The same goes for noise that does not change behavior: an unchecked exception in a throws clause, an empty no-arg constructor that is the only constructor of the class, extra blank lines.

Tools that find smells for you

Most smells in this lesson can be detected automatically. Install SonarLint (now called SonarQube for IDE) in IntelliJ IDEA, Eclipse or VS Code to see issues while you type, and run SonarQube Server or SonarQube Cloud on the CI server so that new code is checked before it is merged.

IntelliJ IDEA has built-in inspections for many of the same problems: unused declarations, Optional used as a field or parameter, a stream that can be simplified, a lambda that can be a method reference. Code → Inspect Code runs them for the whole project. Tools find the mechanical smells; the design ones — a class with two responsibilities, a name that lies — still need a human reviewer.

Frequently Asked Questions

Is a code smell the same as a bug?

No. A bug makes the program behave incorrectly; a smell is code that works but is hard to read or risky to change. Smells often lead to bugs later, which is why static analysis tools report both, usually with different severities.

Can I replace collect(Collectors.toList()) with toList() everywhere?

Only where nobody modifies the result. Stream.toList() returns an unmodifiable list, so later add() or sort() calls on it throw UnsupportedOperationException. Collectors.toList() gives no guarantee about mutability, but in practice returns an ArrayList. More in Readable streams.

Why is Optional not recommended for fields and method parameters?

It was designed for return values. As a field it adds an object per instance and is not Serializable; as a parameter it forces callers to wrap values and still allows passing null instead of an Optional. Use overloads or default values for parameters and plain nullable fields with a getter that returns Optional.

When is it OK to use peek()?

For temporary debugging output while you investigate a pipeline, and in tests that check how many elements pass a stage. Do not put business logic, counters or state changes in peek(): the stream may skip it, for example when count() can be computed from the source.

Practice

Reinforce this lesson with hands-on tasks, each with a level and a time estimate.

All module tasks →

Comments

Please log in or register to have a possibility to add comment.