Anthony J
Anthony J

Reputation: 581

Optimisation of searching HashMap with list of values

I have a map in which values have references to lists of objects.

//key1.getElements()  - produces the following
[Element N330955311 ({}), Element N330955300 ({}), Element N3638066598 ({})]

I would like to search the list of every key and find the occurrence of a given element (>= 2).

Currently my approach to this is every slow, I have a lot of data and I know execution time is relative but it takes 40seconds~.

My approach..

public String occurance>=2 (String id)
//Search for id
//Outer loop through Map 
//get first map value and return elements 
    //inner loop iterating through key.getElements()
      //if match with id..then iterate count
      //return Strings with count == 2 else return null

The reason why this is so slow is because I have a lot of ids which I'm searching for - 8000~ and I have 3000~ keys in my map. So its > 8000*3000*8000 (given that every id/element exists in the key/valueSet map at least once)

Please help me with a more efficient way to make this search. I'm not too deep into practicing Java, so perhaps there's something obvious I'm missing.

Edited in real code after request:

public void findAdjacents() {
        for (int i = 0; i < nodeList.size(); i++) {
            count = 0;
            inter = null;
            container = findIntersections(nodeList.get(i));

            if (container != null) {
                intersections.add(container);
            }
        }
        }

public String findIntersections(String id) {
        Set<Map.Entry<String, Element>> entrySet = wayList.entrySet();
        for (Map.Entry entry : entrySet) {
            w1 = (Way) wayList.get(entry.getKey());
            for (Node n : w1.getNodes()) {
                container2 = String.valueOf(n);
                if (container2.contains(id)) {
                    count++;
                }
                if (count == 2) {
                    inter = id;
                    count = 0;
                }
            }
        }
    if (inter != (null))
        return inter;
    else
        return null;
}

Upvotes: 0

Views: 361

Answers (1)

Aritra Chatterjee
Aritra Chatterjee

Reputation: 460

Based on the pseudocode provided by you, there is no need to iterate all the keys in the Map. You can directly do a get(id) on the map. If the Map has it, you will get the list of elements on which you can iterate and get the element if its count is > 2. If the id is not there then null will be returned. So in that case you can optimize your code a bit.

Thanks

Upvotes: 1

Related Questions