Skip to content

[java] UnnecessaryCast: False positive for anonymous class in Stream.map() with toList() #6409

Closed

Description

@kna

Affects PMD Version:
7.20.0

Rule:
UnnecessaryCast

Description:
PMD reports UnnecessaryCast for a cast that is actually required for successful compilation when returning an anonymous class implementing an interface from a Stream.map() lambda expression followed by .toList().

The cast is necessary due to how Java's type inference handles anonymous classes - without it, the code fails to compile with a type incompatibility error.

Code Sample demonstrating the issue:

package org.example;

import java.util.List;

public class Sample {
    public List<Foo> calc(final List<Integer> list) {
        return list.stream().map(i -> (Foo) new Foo(){}).toList();
    }
    interface Foo{}
}

Expected outcome:

PMD reports a violation at line 7, but that's wrong. That's a false positive.

If you delete the cast, you fail to compile it whith this error:

error: incompatible types: List<<anonymous Foo>> cannot be converted to List<Foo>
        return list.stream().map(i -> new Foo(){}).toList();

Running PMD through:
Gradle
Java 17

Activity

  1. added
    a:false-positive
    on Jan 21, 2026
  2. changed the title [-][java] UnnecessaryCast false positive: Cast required for anonymous class in Stream.map() with toList()[/-] [+][java] UnnecessaryCast: False positive for anonymous class in Stream.map() with toList()[/+] on Jan 22, 2026
  3. zbynek commented on Jan 24, 2026

    @zbynek
    Contributor

    You don't need the cast if you use

    list.stream().<Foo>map(i -> new Foo(){}).toList();
    

    Not sure if PMD should force you to do that though.

  4. added
    in:type-resolution
    on Oct 29, 2026
  5. added this to the 7.29.0 milestone on Oct 29, 2026
  6. added a commit that references this issue on Oct 29, 2026
    1f563e2
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-positivein:type-resolution

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions