Search code examples
javahashmapmultiple-columnstreemap

TreeMap with two keys


I am making a simple 2D java sidescroller, and right now, I have a HashMap where I have a class Location as the key, and Entity as the value. I want to be able to store the Entity objects in a TreeMap (or something similar) where I will have 2 keys: double x and double y. and be able to get all values, where first key is between specific numbers, and the second key too. So far I only found TreeMap, but it only allows me to have 1 double as the key. Is there a way in Java to implement that without having to loop through every key, (suck as Location) and checking if the 2 numbers in it are within the specified bounds?


Solution

  • While it's not pretty - one way to do this is with a TreeMap<Double, TreeMap<Double, Entity>>. Then to get all entities within a square, you can do map.subMap(minX, maxX).subMap(minY, maxY).values();