Java8:使用流将一个映射转换为另一个映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25712591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java8: convert one map to an another using stream
提问by Antonio
I need to convert a Java HashMap
to an instance of TreeMap
(including map contents)
我需要将 Java 转换HashMap
为TreeMap
(包括地图内容)的实例
HashMap<String, Object> src = ...;
TreeMap<String, Object> dest = src.entrySet().stream()
.filter( ... )
.collect(Collectors.toMap( ???, ???, ???, TreeMap::new));
What should I put in place of ???
to make this code compilable?
我应该用什么代替???
以使此代码可编译?
采纳答案by NiematojakTomasz
From Collectors.toMap(...) javadoc:
从Collectors.toMap(...) javadoc:
* @param keyMapper a mapping function to produce keys
* @param valueMapper a mapping function to produce values
* @param mergeFunction a merge function, used to resolve collisions between
* values associated with the same key, as supplied
* to {@link Map#merge(Object, Object, BiFunction)}
* @param mapSupplier a function which returns a new, empty {@code Map} into
* which the results will be inserted
For example:
例如:
HashMap<String, Object> src = ...;
TreeMap<String, Object> dest = src.entrySet().stream()
.filter( ... )
.collect(Collectors.toMap(Map.Entry::getKey , Map.Entry::getValue, (a,b) -> a, TreeMap::new));
回答by rogue lad
Just another way to convert map into stream:
将地图转换为流的另一种方法:
Use of Stream.of(t)
Stream.of(t) 的使用
HashMap<String, Object> src = ...;
TreeMap<String, Object> dest = Stream.of(src)
.filter( ... )
.collect(Collectors.toMap(Map.Entry::getKey , Map.Entry::getValue, (a,b) -> a, TreeMap::new));