Search code examples
javaguavaapache-commons-collection

A Map<String, List<String>> implementation, exposing a view Map of "last values"


I'm looking at various google-collections (or also Apache commons collections) classes, and I'd fancy some help in finding the most appropriate Map implementation for my use case. I'm not interested in home-grown maps.

Here are some requirements:

  • I have a Map<String, List<String>> data structure (A)
  • Most of the time, I want to expose a Map<String, String> read-only view (B).
  • (B) features:
    • Keys in (B) correspond to keys in (A)
    • Values in (B) correspond to the "last values in (A)", i.e. B.get(X) == A.get(X).get(A.get(X).size() - 1)
    • Values in (A) may not be empty lists

I know ArrayListMultimap, but it doesn't expose a view satisfying my requirements for (B).

Any pointers?


Solution

  • I suspect you just want Maps.transformValues from Guava:

    Map<String, String> lastValueView = Maps.transformValues(originalMap,
        new Function<List<String>, String>() {
            @Override
            public String apply(List<String> input) {
                return input.get(input.size() - 1);
            }
        });