How to transform List to Map with Google collections?

前端 未结 5 742
名媛妹妹
名媛妹妹 2021-02-01 12:53

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 collec

5条回答
  •  借酒劲吻你
    2021-02-01 13:07

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

    Maps.asMap(Set, Function) (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, Function) 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.

提交回复
热议问题