如何使用Java8转换映射的每个条目集的键和值?

如何使用Java8转换映射的每个条目集的键和值?,java,hashmap,java-8,java-stream,Java,Hashmap,Java 8,Java Stream,我有一个Map,我想用Java流将它转换成Map 这是我尝试过的,但我认为我的语法错了: myMap.entrySet() .stream() .collect(Collectors.toMap(e -> Type1::new Type1(e.getKey()), e -> Type2::new Type2(e.getValue)))); 也试过 myMap.entrySet() .stream() .collect(Collectors.toMap(new Typ

我有一个
Map
,我想用Java流将它转换成
Map

这是我尝试过的,但我认为我的语法错了:

myMap.entrySet()
.stream()
.collect(Collectors.toMap(e -> Type1::new Type1(e.getKey()), e -> Type2::new Type2(e.getValue))));
也试过

myMap.entrySet()
    .stream()
    .collect(Collectors.toMap(new Type1(Map.Entry::getKey), new Type2(Map.Entry::getValue));
但我一直在运行编译错误。如何进行此转换

myMap.entrySet().stream()
     .map(entry -> new AbstractMap.SimpleEntry(new Type1(entry.getKey()), new Type2(entry.getValue()))
     .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))

或者更优雅地说:

myMap.entrySet().stream()
     .map(this::getEntry)
     .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

private Map.Entry<Type1, Type2> getEntry(Map.Entry<String, String> entry) { 
     return new AbstractMap.SimpleEntry(new Type1(entry.getKey()), new Type2(entry.getValue());
}
myMap.entrySet().stream()
.map(this::getEntry)
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
private Map.Entry getEntry(Map.Entry){
返回新的AbstractMap.SimpleEntry(新的Type1(entry.getKey()),新的Type2(entry.getValue());
}

看起来你真正想要的是

 myMap.entrySet()
     .stream()
     .collect(Collectors.toMap(
         e -> new Type1(e.getKey()), e -> new Type2(e.getValue())));

尽管我承认这确实很难说。

有必要使用流吗?通常情况下,如果您想简化它,最简单的方法是从纯代码开始,然后使用流。对于您的任务,您可能希望在stream()之后调用map().Streams和lambda函数对用户来说是一种痛苦,因为键入对用户来说是模糊的。这是我的警告。祝你好运。还有一个方向正确的引用…你对
collect
collector.toMap
的语法是正确的。我用这个collect尝试了类似的代码:
Map x=Map.entrySet().stream().collector(Collectors.toMap(e->Integer.parseInt(e.getKey()),e->Integer.parseInt(e.getValue())
。它可以工作。什么时候没有arg
toMap
收集器了?有。如果我必须对数据进行一些逻辑处理,然后将其收集到map,我更喜欢先映射然后再收集。也许,问题源于在处理Java 8特定代码时查看Java 7 API。在那里,你甚至找不到
收集器在使用Java8API参考时,您会注意到……公平地说,如果有一个,那么它将非常有用,而且提供它也不会那么困难,例如,
public static Collector toMap(){return Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue);}
…请注意,您编辑的代码包含错误。由于
getEntry
返回最抽象的类型
Map.Entry
,因此您不能在
toMap
中使用引用
AbstractMap.SimpleEntry的函数,即使您知道实例将具有该实际类型。在这种情况下,请正确使用
Map.Entry
反而使代码更短。没有理由在
新表达式之外引用具体类型
AbstractMap.SimpleEntry