views:

189

answers:

2

I didn't find such a multimap construction... When i want to do this, I iterate over the map, and populate the multimap. Is there an other way ??

final Map<String, Collection<String>> map = ImmutableMap.<String, Collection<String>>of(
            "1", Arrays.asList("a", "b", "c", "c"));
System.out.println(Multimaps.forMap(map));

final Multimap<String, String> expected = ArrayListMultimap.create();
for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {
    expected.putAll(entry.getKey(), entry.getValue());
}
System.out.println(expected);

The first result is "{1=[[a, b, c, c]]}" but I expect {1=[a, b, c, c]}

+1  A: 

UPDATE: For what you're asking, I think you're going to need to fall back to Multimap.putAll.

Hank Gay
Thanks, but when I asked the question, I've already tried some functions of this class...and other ways... but the ONLY things which works for me is to iterate over the map...
Sylvain M
@Sylvian: since you marked this answer accepted, does it mean that your problem is now actually solved? It look like not since you didn't mention that in any way. Just wondering, it would otherwise have been a waste of time for others to post a more detailed/suitable answer.
BalusC
What about `Multimaps.newMultimap(map, new Supplier<List<String>>(){ public List<String> get() { return new ArrayList<String>();}});`
Mark Peters
It does'nt work since Multimaps.newMultimap() required an empty map as first argument
Sylvain M
@Sylvain, ah OK I misunderstood the behaviour of that method.
Mark Peters
Mark - this doesn't do what you think. It only creates a new multimap based on the underlying maop instance. It expects map to be empty, and throws an exception otherwise
@Mark Peters Yeah, the Javadoc on that suite of methods could use some help. That requirement should be on the param docs, not just in the exception docs.
Hank Gay
@Hank: that's what I also think, but before asking for an improvement or something like that, I would ask the question here :)
Sylvain M
This solution seems to be the right one...
Sylvain M
+3  A: 

Assuming you have

Map<String, Collection<String>> map = ...;
Multimap<String, String> multimap = ArrayListMultimap.create();

Then I believe this is the best you can do

for (String key : map.keySet()) {
  multimap.putAll(key, map.get(key));
}

or the more optimal, but harder to read

for (Entry<String, Collection<String>> entry : map.entrySet()) {
  multimap.putAll(entry.getKey(), entry.getValue());
}
Kevin Bourrillion
That's exactly what I did !Be just warned, as Kevin pointed it here http://groups.google.com/group/guava-discuss/browse_thread/thread/255cabbcc70925b3 a Multimap is a Map, and then if in the original Map, you have an empty iterable as value, then, the entry "<key, EMPTY_LIST>" will not be added the the multimap
Sylvain M