Java8: convert one map to an another using stream

2019-02-11 14:10发布

I need to convert a Java HashMap to an instance of TreeMap (including map contents)

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?

1条回答
我命由我不由天
2楼-- · 2019-02-11 14:54

From 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));
查看更多
登录 后发表回答