在 Java 8 中,如何转换 Map<K,V>到另一个地图<K,V>使用拉姆达? [英] In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

查看:26
本文介绍了在 Java 8 中,如何转换 Map<K,V>到另一个地图<K,V>使用拉姆达?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始研究 Java 8 并尝试使用 lambdas,我想我会尝试重写我最近写的一个非常简单的东西.我需要将字符串到列的映射转换为另一个字符串到列的映射,其中新映射中的列是第一个映射中列的防御副本.列有一个复制构造函数.我到目前为止最接近的是:

I've just started looking at Java 8 and to try out lambdas I thought I'd try to rewrite a very simple thing I wrote recently. I need to turn a Map of String to Column into another Map of String to Column where the Column in the new Map is a defensive copy of the Column in the first Map. Column has a copy constructor. The closest I've got so far is:

    Map<String, Column> newColumnMap= new HashMap<>();
    originalColumnMap.entrySet().stream().forEach(x -> newColumnMap.put(x.getKey(), new Column(x.getValue())));

但我相信一定有更好的方法来做到这一点,如果您提供一些建议,我将不胜感激.

but I'm sure there must be a nicer way to do it and I'd be grateful for some advice.

推荐答案

您可以使用 收藏家:

import java.util.*;
import java.util.stream.Collectors;

public class Defensive {

  public static void main(String[] args) {
    Map<String, Column> original = new HashMap<>();
    original.put("foo", new Column());
    original.put("bar", new Column());

    Map<String, Column> copy = original.entrySet()
        .stream()
        .collect(Collectors.toMap(Map.Entry::getKey,
                                  e -> new Column(e.getValue())));

    System.out.println(original);
    System.out.println(copy);
  }

  static class Column {
    public Column() {}
    public Column(Column c) {}
  }
}

这篇关于在 Java 8 中,如何转换 Map&lt;K,V&gt;到另一个地图&lt;K,V&gt;使用拉姆达?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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