Search code examples
javaguavaimmutable-collections

Is there a with() method inside ImmutableMap?


I am watching the video (https://www.youtube.com/watch?v=ZeO_J2OcHYM) and find that we can initialize the ImmutableMap using the with() method. See below:

public static final ImmutableMap<String, Integer>
    ENGLISH_TO_INT = ImmutableMap
        .with("four", 4)
        .with("eight", 8)
        .with("fifteen", 15)
        .with("sixteen", 16)
        .with("twenty-three", 23)
        .with("forty-two", 42)
        .build();

However, when I check the API of ImmutableMap, I didn't find a with() method. Is that method been deprecated?


Solution

  • I am guessing they deprecated it in favor of explicitly creating a builder, and using put to mirror the method of the same name on a Map. I am looking at the release notes, but I haven't found anything explicit, yet. That video is old, and Guava has a much more recent version.

    According to the Javadoc, it has been there since version 2.0, when it was merged from google-collections. Taking a closer look at the video shows that they are demonstrating with version 0.9.

    Looking at the releases of google-collections, I don't see any listed changes and I don't see it in any of the Javadoc, so I am guessing it didn't make it into any of the official releases.

    If you need to construct an ImmutableMap with a bunch of entries, you can use the builder() call. There are also several of() methods that can generate maps of a limited size (I think 5?).

    public static final ImmutableMap<String, Integer>
        ENGLISH_TO_INT = ImmutableMap.<String, Integer>builder()
        .put("four", 4)
        .put("eight", 8)
        .put("fifteen", 15)
        .put("sixteen", 16)
        .put("twenty-three", 23)
        .put("forty-two", 42)
        .build();