Java集合/ map应用方法相当吗? [英] Java collection/map apply method equivalent?

查看:136
本文介绍了Java集合/ map应用方法相当吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个函数应用于Java集合,在这种特殊情况下是一个映射。有一个很好的方法来做到这一点吗?我有一个地图,并希望只是对地图中的所有值运行trim(),并让地图反映更新。

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 the values in the map and have the map reflect the updates.

推荐答案

使用Java 8的lambdas,这是一个线程:

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

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

为了历史,这里有一个没有lambdas的版本:

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

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

或更一般地:

interface Function<T> {
  T operate(T val);
}

public static <T> void replaceValues(Map<?, T> map, Function<T> f)
{
  for (Map.Entry<?, T> e : map.entrySet())
    e.setValue(f.operate(e.getValue()));
}

Util.replaceValues(myMap, new Function<String>() {
  public String operate(String val)
  {
    return (val == null) ? null : val.trim();
  }
});

这篇关于Java集合/ map应用方法相当吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆