Java collection/map apply method equivalent?

后端 未结 8 556
爱一瞬间的悲伤
爱一瞬间的悲伤 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:15

    With Java 8's lambdas, this is a one liner:

    map.replaceAll((k, v) -> v.trim());
    

    For the sake of history, here's a version without lambdas:

    public void trimValues(Map map) {
      for (Map.Entry e : map.entrySet()) {
        String val = e.getValue();
        if (val != null)
          e.setValue(val.trim());
      }
    }
    

    Or, more generally:

    interface Function {
      T operate(T val);
    }
    
    public static  void replaceValues(Map map, Function f)
    {
      for (Map.Entry e : map.entrySet())
        e.setValue(f.operate(e.getValue()));
    }
    
    Util.replaceValues(myMap, new Function() {
      public String operate(String val)
      {
        return (val == null) ? null : val.trim();
      }
    });
    

提交回复
热议问题