mota
mota

Reputation: 35

How to transform Iterable<Map.Entry<A,B>> to Map<A,B> using Guava?

I was able to do that by doing the following :

Iterable<Map.Entry<A,B>> entryIterable
Map<A, B> aBMap = newHashMap();
for (Map.Entry<A, B> aBEntry : entryIterable) {
   aBMap.put(aBEntry.getKey() , aBEntry.getValue());
}

Is there an easier way to do this using Guava?

Upvotes: 4

Views: 2513

Answers (3)

thSoft
thSoft

Reputation: 22650

This has been implemented in Guava 19.0, see ImmutableMap.copyOf(Iterable).

Upvotes: 1

maaartinus
maaartinus

Reputation: 46372

No, this was refused, see the Idea Graveyard:

Create a map from an Iterable<Pair>, Iterable<Map.Entry>, Object[] (alternating keys and values), or from List<K> + List<V>

Note that we may still add ImmutableMap.copyOf(Iterable<Entry>).

Upvotes: 6

Louis Wasserman
Louis Wasserman

Reputation: 198014

Only a wee bit easier:

ImmutableMap.Builder<A, B> builder = ImmutableMap.builder();
for (Map.Entry<A, B> entry : entries) {
  builder.put(entry); // no getKey(), no getValue()
}
return builder.build();

Upvotes: 1

Related Questions