Skip to content

[java] UselessPureMethodCall: False positive for Stream.forEach #6781

Closed

Description

@estekhin

Affects PMD Version: 7.25.0

Rule: https://docs.pmd-code.org/pmd-doc-7.25.0/pmd_rules_java_errorprone.html#uselesspuremethodcall

Description:

PMD 7.25.0 reports some usages of Stream.forEach when forEach is used to add elements to an existing collection declared as var. The same code works ok when that collection type is declared explicitly.

The only difference between methods in the sample code is the declaration of the result variable.

PMD 7.24.0 works fine.

Code Sample demonstrating the issue:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class UselessPureMethodCallStreamForEach {

    List<Object> ok(List<Object> source) {
        ArrayList<Object> result = source.stream()
            .collect(Collectors.toCollection(ArrayList::new));

        source.stream()
            .forEach(result::add);

        return result;
    }

    List<Object> triggersUselessPureMethodCall(List<Object> source) {
        var result = source.stream()
            .collect(Collectors.toCollection(ArrayList::new));

        // the line below triggers
        // UselessPureMethodCallStreamForEach:25 Rule:UselessPureMethodCall Priority:3 Do not call pure method forEach if the result is not used..
        source.stream()
            .forEach(result::add);

        return result;
    }

}

Expected outcome:

PMD should not report UselessPureMethodCall for this code.

Running PMD through: Maven

Activity

  1. added
    a:false-positive
    on Jun 15, 2026
  2. UncleOwen commented on Jun 15, 2026

    @UncleOwen
    Member

    A side-effect of the changes to InvocationMatcher in #6712.

    In JavaRuleUtil.isKnownPure(), KNOWN_PURE_METHODS.anyMatch(call) now returns true (since the argument isn't resolved) and !call.getMethodType().getReturnType().isVoid() also returns true (also because the argument isn't resolved). @zbynek I don't think that was intended?

  3. changed the title [-][java] UselessPureMethodCall: False-Positive for Stream.forEach[/-] [+][java] UselessPureMethodCall: False positive for Stream.forEach[/+] on Jun 18, 2026
  4. added this to the 7.26.0 milestone on Jun 22, 2026
  5. added a commit that references this issue on Jun 22, 2026
  6. added a commit that references this issue on Jun 22, 2026
    d82c36d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positive

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions