【问题标题】:Java-How to implement a custom map(Function<? super T, ? extends R> mapper) that can transform values of a Map given a functionJava-如何实现自定义映射(Function<? super T, ? extends R> mapper),它可以在给定函数的情况下转换 Map 的值
【发布时间】:2019-09-21 23:02:46
【问题描述】:

我有一个自定义的排序地图。我想使用 map 函数转换地图中的每个值。我知道我可以使用 java 8 stream().map(function) 来实现这一点。但我想了解上面的 map(function) 是如何工作的并编写一个自定义函数。

我已经阅读了几篇文章,但我没有找到一篇解释清除的文章。

我是怎么做的:

SortedMap<String, Integer> items = new TreeMap();//TreeMap is a custom implementation
        items.put("item1", 2);
        items.put("item2", 1);

      SortedMap<String, Integer> transformedItems=items.entrySet().stream().collect(
             Collectors.toMap(
                   ( Map.Entry<String, Integer> entry)->entry.getKey(),//pick each key as it is
                     ( Map.Entry<String, Integer> entry)->entry.getValue()*2, //transform the value here.
                     (val1, val2) -> { throw new RuntimeException("Not expecting duplicate keys"); },
                     ()->new TreeMap<>()

我想怎么做:

SortedMap<String, Integer> items = new TreeMap();
        items.put("item1", 2);
        items.put("item2", 1);

      SortedMap<String, Integer> transformedItems=items.customMap(value->value*2)

这里的挑战是写customMap(function)

【问题讨论】:

  • @Andreas 我有 TreeMap 的自定义实现,所以我可以添加一个方法
  • 如果您有自定义实现,则可以在答案中添加建议的方法,仅将valueMapper 作为参数。
  • SortedMap&lt;String, Integer&gt; result = new TreeMap(); items.forEach((key, value) -&gt; result.put(key, yourFunction.apply(value))); 这就是你想要的吗?这个逻辑并不是一个神奇的秘密。这是right in the official documentation

标签: java collections java-stream


【解决方案1】:

您可以创建一个独立的static 方法,该方法采用值映射函数。该方法几乎可以完成您的代码所做的事情:

public static <K, V, R> TreeMap<K, R> mapValues(Map<K, V> map, Function<V, R> valueMapper) {
    return map.entrySet().stream().collect(
            Collectors.toMap(Map.Entry::getKey,
                             e -> valueMapper.apply(e.getValue()),
                             (a, b) -> { throw new AssertionError("Not expecting duplicate keys"); },
                             TreeMap::new));
}

测试

SortedMap<String, Integer> items = new TreeMap<>();
items.put("item1", 2);
items.put("item2", 1);

SortedMap<String, Integer> transformedItems = mapValues(items, value -> value * 2);

System.out.println(transformedItems);

输出

{item1=4, item2=2}

注意映射值如何具有不同的类型,例如

SortedMap<String, Double> transformedItems = mapValues(items, value -> value * 2.5);

System.out.println(transformedItems);

输出

{item1=5.0, item2=2.5}

【讨论】:

  • 不应该首选返回 MapSortedMap(返回类型),尽管在 mapValues 中实现?
  • @Naman 也许,也许不是,这完全由你决定。
猜你喜欢
  • 1970-01-01
  • 2017-07-06
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 2020-01-29
  • 2016-10-11
  • 2012-01-11
  • 1970-01-01
相关资源
最近更新 更多