1

I want to create multimap with keys as a Strings and values as a Sets

Multimap<String, Set<String>> = ???

when I put keys, and values in this way:

multimap.put("e", set1);
multimap.put("x", set2);
multimap.put("a", set3);
multimap.put("m", set4);
multimap.put("p", set5);
multimap.put("l", set6);
multimap.put("e", set7);

I want to receive exactly this same order with this same sets, so it means:

"e" -> set1
"x" -> set2
"a" -> set3
"m" -> set4
"p" -> set5
"l" -> set6
"e" -> set7

I'm new inn guava, so could anybody write how to implement this Multimap to set duplicated keys in it and receive values in this order?

3
  • You can't put a Set as the value of such a Multimap. Only a String. It seems like you simply want a List<Item> or a LinkedHashSet<Item>, where Item contains two Strings. Please better explain what you actually want to achieve.
    – JB Nizet
    Aug 15, 2013 at 10:47
  • Could I create CustomObject instead of Set<String> and use multimap? What I want to achieve is to have Strings as a key (which will be duplicated, and some properties to each one. When I returned keys from map/multimap the order of inserting them must be saved. Aug 15, 2013 at 13:20
  • 2
    @JBNizet: Sure, you can use a Set as the value of a Multimap, you'll just get something like a Map<Key, Set<Set<Value>>. But that may not be what you want. Aug 15, 2013 at 16:10

1 Answer 1

4

LinkedHashMultimap.entries() preserves the exact order the entries were added to the multimap.

5
  • and what about storing duplicated keys? From Javadoc Class LinkedHashMultimap: Implementation of Multimap that does not allow duplicate key-value Aug 16, 2013 at 18:48
  • It really depends what you want, about which you haven't been clear at all. Do you want something closer to a Map<String, List<String>>? A Map<String, Set<String>>? A Map<String, Set<Set<String>>>? Aug 16, 2013 at 18:49
  • Sorry, maybe I wasn't clear enough. I want something like Map<String, List<String>> or Map<String, Set<String>> with duplicated keys and with the exact order of adding. Aug 16, 2013 at 19:19
  • What do you mean, "duplicated keys"? SetMultimap says that if you already have the key "foo" mapped to the value "bar", you can't add another value "bar" for the key "foo", and ListMultimap doesn't have that restriction (because its "value collections" are Lists, not Sets.) But all Multimaps will merge all the values associated with any individual key. Aug 16, 2013 at 19:29
  • I've just checked and Multimap<String, List<String>> multimap = LinkedHashMultimap.create() with LinkedHashMultimap.entries() resolved my problem. Thanks, and sorry for misunderstanding. Aug 17, 2013 at 5:25

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.