Skip to content

FR: Prefer ImmutableSet.toImmutableSet() over Collectors.toSet() for public static final fields #620

Open
@iamdanfox

Description

@iamdanfox

What happened?

In an internal library, we a nice public static final field:

public static final Set<String> WHITELISTED_HEADERS = ImmutableSet.of(
    HttpHeaders.ACCEPT,
    ...
).stream().map(String::toLowerCase).collect(Collectors.toSet());

But it turns out that Collectors.toSet() gives us a mutable HashMap, so anyone could actually just access this WHITELISTED_HEADERS field and add/remove stuff!!

What did you want to happen?

I think we should write an error-prone check to just prefer the toImmutableSet() collector!

 public static final Set<String> WHITELISTED_HEADERS = ImmutableSet.of(
     HttpHeaders.ACCEPT,
     ...
-).stream().map(String::toLowerCase).collect(Collectors.toSet());
+).stream().map(String::toLowerCase).collect(ImmutableSet.toImmutableSet());

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions