Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

import java.util.

*;
import java.util.stream.Collectors;

public class UndirectedGraph{


int numOfNodes;
Map<Integer,List<Integer>> adjList = new HashMap();

public static void main(String[] args){


UndirectedGraph myGraph = new UndirectedGraph();
myGraph.addVertex(0);
myGraph.addVertex(1);
myGraph.addVertex(2);
myGraph.addVertex(3);
myGraph.addVertex(4);
myGraph.addVertex(5);
myGraph.addVertex(6);
System.out.println("Total num of nodes: "+myGraph.numOfNodes);
myGraph.showConnections();
myGraph.addEdge(0,1);
myGraph.addEdge(0,2);
myGraph.showConnections();
}

void addVertex(Integer vertex){


this.adjList.put(vertex, new ArrayList<Integer>());
numOfNodes++;
}

void addEdge(Integer vertex1, Integer vertex2){


if(!this.adjList.containsKey(vertex1) || !
this.adjList.containsKey(vertex2)){
throw new IllegalArgumentException("Invalid Edge as nodes must be
created before creating an edge");
}
List<Integer> vertex1Edges = this.adjList.get(vertex1);
vertex1Edges.add(vertex2);

List<Integer> vertex2Edges = this.adjList.get(vertex2);


vertex2Edges.add(vertex1);
}

void showConnections(){
for(Integer vertex : this.adjList.keySet()){
String values = this.adjList.get(vertex).stream().filter(key->
key != null).map(String :: valueOf).collect(Collectors.joining(","));
System.out.println("Connections for node: "+vertex+" are
"+values);
}
}
}

You might also like