To generate a random graph efficiently, you can use Erdős–Rényi model.
It is a classical approach in graph theory. The Java code (using graphstream library) to generate a random graph is something like:
Graph g = new SingleGraph("Erdos-Renyi model");
// adding the first nodes
g.addNode("0");
g.addNode("1");
// creates the first edge
g.addEdge("0_1", "0", "1");
Integer i = 2;
while(i < numNodes) {
Node source = g.addNode(i.toString());
Node dest = g.getNode(random.nextInt(i)+"");
g.addEdge(source.getId() + "_" + dest.getId(), source.getId(), dest.getId());
i++;
}
There are also other models to generate graphs such as the Barabási–Albert model. This model generates a graph where the more connected a node is, the more likely it is to receive new links (describing the rich get richer phenomenon). The Java code to generate a random graph using Barabási-Albert model is:
Graph g = new SingleGraph("Barabasi–Albert model");
g.addNode("0");
g.addNode("1");
g.addEdge("0_1", "0", "1");
int sumDegree = 2;
Integer i = 2;
while(i < numNodes) {
Node source = g.getNode(i.toString());
if(source == null) {
source = g.addNode(i.toString());
}
Node dest = g.getNode(random.nextInt(i)+"");
double probability = dest.getDegree() * 1.0/sumDegree;
double r = nextDouble();
if(probability > r) {
g.addEdge(source.getId() + "_" + dest.getId(), source.getId(), dest.getId());
sumDegree = sumDegree + 2;
i++;
}
}
Another famous approach is to generate a random graph with small-world properties by using the Watts–Strogatz model. In this case, most nodes are not neighbors of one another. However, the neighbors of any given node are likely to be neighbors of each other and most nodes can be reached from every other node by a small number of hops.
As you see, there are several possibilities to generate random graphs. Depending on the network characteristics required, a specific model should be used.