user2731629
user2731629

Reputation: 412

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?

Upvotes: 0

Views: 694

Answers (2)

Daniel Bickler
Daniel Bickler

Reputation: 1140

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());
}

Upvotes: 5

kk.
kk.

Reputation: 3945

You can use List inside the map to store multiple values for the same key.

    public class Test {

    public static void main(final String[] args) {
        LinkedList<Values> list = new LinkedList<Values>();
        list.add(new Values("a", 1));
        list.add(new Values("b", 2));
        list.add(new Values("a", 3));
        System.out.println(list);
    }
}

class Values {
    String key;
    int value;

    public Values(final String key, final int value) {
        super();
        this.key = key;
        this.value = value;
    }

    @Override
    public String toString() {
        return key + "," + value;
    }
}

The output of this program is:

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

I hope this is how you want it.

Upvotes: 1

Related Questions