简体   繁体   中英

Java traverse a large HashMap like a graph

I have a large HashMap<String,Set<String>> , say like this:

    {INDIANBATSMAN=[INDIAN, CRICKETER], COMPANY=[THING],
 INDIAN=[LIVING], LIVING=[THING], PERSON=[LIVING],
 CRICKETER=[PERSON], CANADIAN=[LIVING], SCANDINAVIAN=[LIVING]}

This actually corresponds to a graph structure, meaning there are edges between each key to its set of values. I want to traverse each link and find all the nodes reachable from the initial node as set of values for my keys.

Like,

INDIANBATSMAN=[INDIAN,LIVING,THING,CRICKETER,PERSON]

What should be the most efficient way to get this done? (currently, I am converting it to an adjacency matrix, which is really inefficient as my map is huge.)

Your current representation ( Map<String, Set<String>> ) is called an adjacency list and is perfectly suitable for a standard traversal algorithms such as breadth-first or depth-first.

Something like this should do:

visited = empty set
q = empty list
q.add(startNode)
visited.add(startNode)
while (q is non-empty)
    Node n = q.removeFirst()
    process(n)
    Set<String> children = yourMap.get(n)
    for (Node child : children)
        if (! visited contains child)
            visited.add(n)
            q.add(child)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM