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?

Binyamin Regev
  • 914
  • 5
  • 19
  • 31
Anthony
  • 12,407
  • 12
  • 64
  • 88

2 Answers2

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));
NiematojakTomasz
  • 2,433
  • 20
  • 23
  • Does this also work with a parallelStream or do we have to use ConcurrentSkipList then? – KIC May 31 '15 at 09: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." https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap-java.util.function.Function-java.util.function.Function- – NiematojakTomasz Aug 12 '15 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));
rogue lad
  • 2,413
  • 2
  • 29
  • 32