0

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?

1
  • You can create a wrapper class by extending LinkedHashMultiMap and add an array as one of its fields that keeps track on the order exactly like you want it too Commented Jun 12, 2017 at 13:59

2 Answers 2

5

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

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.

3
  • I need a flattened version by preserving the insertion order like [a,1,b,2,a,3] @Krishna Kuntala.. If I flatened your output, I wont get the order. right! Commented Jun 12, 2017 at 14:08
  • 1
    @user2731629 I hope my updated answer solves your problem with the use of object and a linked list instead of Linked hash map.
    – kk.
    Commented Jun 12, 2017 at 14:18
  • Sorry!!.. Its contains Duplicates. I dont want any duplicate values. if you add a a,3 again , It shouldnt add it. Thats why I was using SetMuliMap. Commented Jun 12, 2017 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.