1

I have a nested map (map in/of map) with two string keys. Essentially what I do is that I have a set of nodes and I find the shortest route between them. However I need to store them and later use them, so I did the following:

private Map<String, Map<String,Object>> TravelTime = 
new HashMap<String, Map<String,Object>>();

I use a loop to give values to this Map, where ParkingDests is a set of keys (String) of another HashMap:

ParkingDests = ParkingAttributes.keySet().size();
for (int i = 0;i< ParkingDests; i++){
    for (int j = 0;j< ParkingDests; j++){

        <code> TravelTime.put(keyone,keytwo,Shortest) </code>

    }
}

I suppose what I need is something like:

TraveTime.put(ParkingDests(i),ParkingDest(j), ShortestRoute)

However I cannot find a way to do it. I am aware of the Guava Table (and I know that it is exactly what I need), however I would prefer to find a solution in this context.

Manos C
  • 333
  • 4
  • 16

2 Answers2

3

You want to check to see if the secondary HashMap is added in before you add a new route. Here, I'm assuming ParkingDests is a String array. I also assume, that your tags means you're wrapping this loop in some code that generates the ShortestRoute object. Definitely no need to store it as a generic Object, but I'm sure you were just simplifying your question nicely for our benefit :)

for (int i = 0;i< ParkingDests; i++){
    for (int j = 0;j< ParkingDests; j++){

        <code>
        second = TravelTime.get(ParkingDests[i])
        if(second == null) {
            second = new HashMap<String, Object>()
            TravelTime.put(ParkingDests[i], second);
        }
        second.put(ParkingDests[j],Shortest);
        </code>

    }
}

Also note, I recommend against using the keySet as ParkingDests like your edited question. You don't get guaranteed order from that. You should keep the ParkingDests as an array.

sdanzig
  • 4,510
  • 1
  • 23
  • 27
  • I think this is it! I changed the ParkingDests to arrays tnx for the advice!! Indeed I scaled my code and indeed thats what it does ;) – Manos C Oct 26 '13 at 11:39
1

I would suggest using a Graph data structure. You could use JGraphT. It has an implementation for the Dijkstra Algorithm which calculates the shortest path. The nodes would be your ParkingDests and the weight of the edges would be your traveltime of distance. The optimal route would be a subgraph. Have fun.

  • I use the Graph structure to calculate the shortest path, but I need to store the cost/route for the Origin-Destination to be used for some specific pairs as an object that contains travel information from a node to all others ;). Thank you very much for the suggestion. – Manos C Oct 26 '13 at 12:05