6

My app uses a TreeMap to keep data sorted and have log(n) lookups & inserts. This works great in the general case while the app is running, but when the app first starts, I need to initialize the TreeMap with several million longs that I get in sorted order (ascending).

Since these initialization values are already sorted, is there any way to insert them into the TreeMap without paying the log(n) cost of tree insertion and re-balancing?

Yevgeniy Brikman
  • 7,399
  • 4
  • 38
  • 55

1 Answers1

11

Sure! The TreeMap.putAll method (and the TreeMap constructor that takes a SortedMap) calls a method called buildFromSorted internally, which is described in the docs as: "Linear time tree building algorithm from sorted data", so that sounds like it does what you want.

Just give the putAll method something that implements Map, but where the map's entryset iterator (Map.entrySet().iterator()) returns your list of sorted values.

trashgod
  • 196,350
  • 25
  • 213
  • 918
Neil
  • 1,644
  • 1
  • 17
  • 29
  • Thanks, this is exactly what I needed, although it'll take some wrangling to turn my list of initialization numbers into something that looks like a SortedMap. – Yevgeniy Brikman Mar 12 '11 at 00:59
  • It might not actually. I edited the answer to say use LinkedHashMap -- you can just put your numbers in that in order, and the iterator will preserve the order you added them. – Neil Mar 12 '11 at 01:11
  • 2
    LinkedHashMap doesn't implement the SortedMap interface, so I don't think the buildFromSorted method would be used. Instead, I had to create an anonymous implementation of SortedMap, an anonymous implementation of Set inside that, an anonymous implementation of iterator inside that and an anonymous implementation of Entry within that. Ugly and verbose as sin, but does the job. – Yevgeniy Brikman Mar 12 '11 at 01:20