oshai oshai - 1 year ago 86
Java Question

how to transform List<String> to Map<String,String> with google collections?

I have a list with strings, and I have a functions to generate value for each key in the list, and I want to create map using a method. is there such function in google collections?

Answer Source

As of 7/26/2012, Guava master contains two new ways to do this. They should be in release 14.0.

Maps.asMap(Set<K>, Function<? super K, V>) (and two overloads for SortedSet and NavigableSet) allows you to view a Set plus a Function as a Map where the value for each key in the set is the result of applying the function to that key. The result is a view, so it doesn't copy the input set and the Map result will change as the set does and vice versa.

Maps.toMap(Iterable<K>, Function<? super K, V>) takes an Iterable and eagerly converts it to an ImmutableMap where the distinct elements of the iterable are the keys and the values are the results of applying the function to each key.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download