在 Java 8 中,我如何转换 Map<K,V>到另一个地图<K,V>使用 lambda?

2022-01-22 00:00:00 lambda java-8 java java-stream map

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

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) {}
  }
}

相关文章