Java8:使用流将一个地图转换为另一个地图
我需要将Java HashMap
转换为TreeMap
的实例(包括地图内容)
HashMap src = ...; TreeMap dest = src.entrySet().stream() .filter( ... ) .collect(Collectors.toMap( ???, ???, ???, TreeMap::new));
我应该代替什么???
使这段代码可编辑?
来自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
例如:
HashMap src = ...; TreeMap dest = src.entrySet().stream() .filter( ... ) .collect(Collectors.toMap(Map.Entry::getKey , Map.Entry::getValue, (a,b) -> a, TreeMap::new));