Search code examples
graph-algorithmgraphstream

How to check if a node is already exist


I want to check if the node is already exist in the graph before adding a new node.

I tried to do it using a foreach loop.But it didnt work.

boolean returnVal = false;
         for (Node node : displayGraph) {
             if (node.getId().equals(n.getId())){
                 returnVal = true;
             }
             else{
                 returnVal =false;
             }
         }

I want to retrieve true if the node is already exist on the graph


Solution

  • Just check what Graph.getNode(String) returns. If no node with that string id exist, then null is returned:

    boolean returnVal = displayGraph.getNode(n.getId()) == null ? false : true;