Java 集合/映射应用方法等效吗? [英] Java collection/map apply method equivalent?

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

问题描述

我想将一个函数应用于 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 集合/映射应用方法等效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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