Java 8:使用流将一个映射转换为另一个映射

时间:2014-09-07 16:49:01

标签: java lambda java-8 java-stream

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

HashMap<String, Object> src = ...;
TreeMap<String, Object> dest = src.entrySet().stream()
        .filter( ... )
        .collect(Collectors.toMap( ???, ???, ???, TreeMap::new));

我应该用什么代替???来使这段代码可编辑?

2 个答案:

答案 0 :(得分:38)

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

答案 1 :(得分:0)

将地图转换为流的另一种方法:

  

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