How to transform List to Map with Google collections?

前端 未结 5 743
名媛妹妹
名媛妹妹 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条回答
  •  -上瘾入骨i
    2021-02-01 13:28

    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 mappedRoles = Maps.uniqueIndex(yourList, new Function() {
      public String apply(String from) {
        // do stuff here
        return result;
      }});
    

提交回复
热议问题