Java8:如何使用流将一个map转换为另一个map?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (975)

我需要将HashMap转换为一个TreeMap实例

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

扫码关注云+社区

领取腾讯云代金券