Search code examples
javaguava

Iterating through all values for a particular key, in order, for a LinkedHashMultiMap


I would like to iterate through the values of a particular key for a LinkedHashMultiMap<String,String> (Guava), by insertion order.

Is this possible? And, if so, how?

Why a LinkedHashMultiMap? Well, my existing data structure was a HashMultiMap and I figured if I changed it to a LinkedHashMultiMap, that would be compatible with my existing code and I could iterate the values somehow.

But looking at the docs, I can't quite figure it out - that said, I'm new to the LinkedHashMultiMap class.


Solution

  • Iteration in insertion order for LinkedHashMultimap is a documented behavior

    Implementation of Multimap that does not allow duplicate key-value entries and that returns collections whose iterators follow the ordering in which the data was added to the multimap.

    and will work out of the box, see wiki page on Multimap implementations:

    | Implementation       | Keys behave like... | Values behave like.. |
    |:---------------------|:--------------------|:---------------------|
    | LinkedHashMultimap** | LinkedHashMap       | LinkedHashSet        |
    
    `**` `LinkedHashMultimap` preserves insertion order of entries,  
    as well as the insertion order of keys, and the set of values associated with any one key.
    

    Code example:

    LinkedHashMultimap<String, String> m = LinkedHashMultimap.create();
    
    m.put("a", "foo");
    m.put("b", "bar");
    m.put("a", "baz");
    
    m.get("a").forEach(System.out::println); // outputs "foo" and "baz"