Java8: convert one map to another map using stream

前端 未结 2 486
抹茶落季
抹茶落季 2021-01-01 13:06

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

HashMap src = ...;
TreeMa         


        
相关标签:
2条回答
  • 2021-01-01 13:25

    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));
    
    0 讨论(0)
  • 2021-01-01 13:32

    Just another way to convert map into stream:

    Use of 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));
    
    0 讨论(0)
提交回复
热议问题