Java collection/map apply method equivalent?

后端 未结 8 565
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 19:27

I would like to apply a function to a Java collection, in this particular case a map. Is there a nice way to do this? I have a map and would like to just run trim() on all t

8条回答
  •  悲&欢浪女
    2020-12-13 20:09

    I don't know a way to do that with the JDK libraries other than your accepted response, however Google Collections lets you do the following thing, with the classes com.google.collect.Maps and com.google.common.base.Function:

    Map trimmedMap = Maps.transformValues(untrimmedMap, new Function() {
      public String apply(String from) {
        if (from != null)
          return from.trim();
        return null;
      }
    }
    

    The biggest difference of that method with the proposed one is that it provides a view to your original map, which means that, while it is always in sync with your original map, the apply method could be invoked many times if you are manipulating said map heavily.

    A similar Collections2.transform(Collection,Function) method exists for collections.

提交回复
热议问题