简体   繁体   English

如何使用Java 8转换Map的每个条目集的键和值?

[英]How to transform the key and value of a each entry set of a Map using Java 8?

I have a Map<String, String> that I want to transform to a Map<Type1,Type2> using Java streams. 我有一个Map<String, String> ,我想使用Java流转换为Map<Type1,Type2>

This is what I tried but I think I am getting the syntax wrong: 这是我尝试过的,但我认为我的语法错误:

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

Also tried 也试过了

myMap.entrySet()
    .stream()
    .collect(Collectors.toMap(new Type1(Map.Entry::getKey), new Type2(Map.Entry::getValue));

But I just keep running compile errors. 但我只是继续运行编译错误。 How do I do this transform? 我该如何改造?

It looks like what you really want is 它看起来像你真正想要的是

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

though I admit it's honestly difficult to tell. 虽然我承认说老实说很难。

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

https://docs.oracle.com/javase/7/docs/api/java/util/AbstractMap.SimpleEntry.html https://docs.oracle.com/javase/7/docs/api/java/util/AbstractMap.SimpleEntry.html

Or more elegantly: 或者更优雅:

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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Map中转换键/值 - How to transform key/value in Map 如何从 map 获取键和值,并使用 Java8 方法对每个键和值执行某些操作 - How to get the key and value from map and perform certain operation on each key and value using Java8 methods Java中的地图输入键 - Map entry key in java 转换映射:将新的键值对添加到现有映射 Java 8 - transform map : add new key value pairs to existing map Java 8 在Java中将List <Map.Entry <Key,Value >>转换为List <Key> - Converting List<Map.Entry<Key, Value>> to List<Key> in Java 映射条目的每个键的流,包含列表作为值 - Stream for each key of map entry, containing list as a value 将地图转换为列表<string> - 作为每个列表条目的“键值” - convert map to list<string> - as “key-value” to each list entry 如何使用Jackson反序列化将每个映射表项的键注入相应的值对象? - How to inject the key of each map entry into the corresponding value object with Jackson deserialization? Java - 如何创建新条目(键、值) - Java - How to create new Entry (key, value) 使用for-each循环和Map.Entry()删除任何在LinkedHashMap实例中等于字符串“world”的键值,但总是得到错误 - remove any key value that is equal to the string “world” in an instance of LinkedHashMap, using for-each loop and Map.Entry(), but always get error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM