26

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?

2
  • 3
    Why not just new TreeMap<>(src)? Commented Sep 7, 2014 at 17:00
  • 1
    Because I need to filter the stream and drop some values
    – Anthony
    Commented Sep 7, 2014 at 17:00

2 Answers 2

44

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));
2
  • Does this also work with a parallelStream or do we have to use ConcurrentSkipList then?
    – KIC
    Commented May 31, 2015 at 9:09
  • @KIC "Implementation Note: The returned Collector is not concurrent. For parallel stream pipelines, the combiner function operates by merging the keys from one map into another, which can be an expensive operation. If it is not required that results are inserted into the Map in encounter order, using toConcurrentMap(Function, Function) may offer better parallel performance." docs.oracle.com/javase/8/docs/api/java/util/stream/… Commented Aug 12, 2015 at 10:10
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.