Search code examples
javaguavamultimap

Flatten SetMultiMap and preserve the insertion order


I am using LinkedHashMultimap in my project. I need to flatten the values while preserving the insertion order. For example with

SetMultimap<String, Integer> m =  LinkedHashMultimap.create();
m.put("a", 1);
m.put("b",2);
m.put("a",3);

I am getting the following output

a : [1,3]
b : 2

But I need

a : 1
b : 2
a : 3

or I need the output to be in a List

[a,1,b,2,a,3]

P.S. I am using LinkedHashMultimap because I don't want duplicate values for a key and I need to preserve the insertion order

How can I do this so I can iterate through the above output for further processing?


Solution

  • Entries are returned and are iterated in the order they were inserted so you can do the following to not lose the benefits of Multimaps.

    for (Map.Entry<String, Integer> entry : m.entries()) {
        System.out.println(entry.getKey() + " : " + entry.getValue());
    }