gpt4 book ai didi

Java8 : convert one map to another map using stream

转载 作者:IT老高 更新时间:2023-10-28 20:51:10 32 4
gpt4 key购买 nike

我需要将 Java HashMap 转换为 TreeMap 的实例(包括 map 内容)

HashMap<String, Object> src = ...;
TreeMap<String, Object> 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<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));

关于Java8 : convert one map to another map using stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25712591/

32 4 0