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

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of