Graph Implementation in Java using Collections

In this post, we will see graph implementation in Java using Collections for weighted and unweighted, graph and digraph.


We know that in an adjacency list representation of the graph, each vertex in the graph is associated with the group of its neighboring vertices or edges. In other words, every vertex stores a list of adjacent vertices.

Directed graph

For example, below is the pictorial representation for corresponding adjacency list for above graph –

Adjacency list


1. Directed Graph (Digraph) Implementation –

Below is Java implementation of a digraph using Adjacency list:


Download   Run Code


(0 –> 1)
(1 –> 2)
(2 –> 0) (2 –> 1)
(3 –> 2)
(4 –> 5)
(5 –> 4)

As evident from above code, an edge is created from src to dest in the adjacency list in a digraph and if the graph is undirected, we also need to create the edge from dest to src in the adjacency list.


2. Weighted Digraph Implementation –

We know that in a weighted graph, every edge will have a weight or cost associated with it as shown below:

Weighted digraph

Below is Java implementation of a weighted digraph using adjacency list. The implementation is similar to that of unweighted digraph, except we’re also storing the weight infomation in adjacency list with every edge.


Download   Run Code


0 –> 1 (6)
1 –> 2 (7)
2 –> 0 (5) 2 –> 1 (4)
3 –> 2 (10)
4 –> 5 (1)
5 –> 4 (3)


Also see:

1. Graph Implementation in C

2. Graph Implementation in C++ using STL

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

newest oldest most voted
Notify of
abhishek kumar

Hi sir,
i need to know why you had used List<List> adj = new ArrayList();
it can be done with List = new LinkedList();
Is there any benefit of it. I’m new to java plzz reply me


Can you please explain the need for line number 38 and 39 (see unweighted one). I am unable to understand why is there a need to allocate space for each edge?
Shouldn’t it be the way that memory be allocated for the number of vertices only?