Data structures that can map a range of keys to a value

Are your ranges non-overlapping? If so you could use a TreeMap: TreeMap<Double, Character> m = new TreeMap<Double, Character>(); m.put(1.0, ‘A’); m.put(2.9, null); m.put(4.0, ‘B’); m.put(6.0, null); m.put(6.5, ‘C’); m.put(10.0, null); The lookup logic is a bit complicated by the fact that you probably want an inclusive lookup (i.e. 2.9 maps to ‘A’, and not undefined): … Read more

Table like java data structure

There is a generic TreeBasedTable class from Google guava library which does exactly what you are asking for. It also offers many other useful utility methods and its usage is shown in the user guide. From the TreeBasedTable docs: Implementation of Table whose row keys and column keys are ordered by their natural ordering or … Read more

What data structures can efficiently store 2-d “grid” data?

Here are a few approaches. I’ll (try to) illustrate these examples with a representation of a 3×3 grid. The flat array +—+—+—+—+—+—+—+—+—+ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | +—+—+—+—+—+—+—+—+—+ a[row*width + column] To access elements on the left or right, subtract or … Read more

Scala: Using HashMap with a default value

Wow, I happened to visit this thread exactly one year after I posted my last answer here. 🙂 Scala 2.9.1. mutable.Map comes with a withDefaultValue method. REPL session: scala> import collection.mutable import collection.mutable scala> mutable.Map[Int, String]().withDefaultValue(“”) res18: scala.collection.mutable.Map[Int,String] = Map() scala> res18(3) res19: String = “”