Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform List<String> to Map<String,String> with Google collections?

I have a list of strings and I have a function to generate a value for each key in the list.

I want to create a map using this function. Can I do this with Google collections?

like image 906
oshai Avatar asked Feb 15 '11 12:02

oshai


People also ask

Can MAP be used on strings?

Map() Function in Golang is used to return a copy of the string given string with all its characters modified according to the mapping function.

What is string string map?

a Map<type, type> is a collection that associates one of the first type with one of the second type. So a Map<String, String> associates a String with another String. This is an instance of generics.


1 Answers

Use Maps.uniqueIndex(Iterable, Function) :

Returns an immutable map for which the Map.values() are the given elements in the given order, and each key is the product of invoking a supplied function on its corresponding value.(from javadoc)

Example:

Map<String,String> mappedRoles = Maps.uniqueIndex(yourList, new Function<String,String>() {   public String apply(String from) {     // do stuff here     return result;   }}); 
like image 118
dogbane Avatar answered Sep 22 '22 07:09

dogbane