It is similar to Graph Representation - Adjacency List (with isDirected)

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Graph {
    private Map<Integer, List<Integer>> adjList = new LinkedHashMap<>();
    private int V;
    private final boolean isDirected;

    public UnweightedAdjListGraph(int n, boolean isDirected) {
        V = n;
        for (int i = 0; i < n; i++) {
            adjMap.put(i, new LinkedList<>());
        }
        this.isDirected = isDirected;
    }

    public boolean addEdge(int i, int j) {
        adjMap.putIfAbsent(i, new LinkedList<>());
        adjMap.get(i).add(j);
        if (!isDirected) {
            adjMap.putIfAbsent(j, new LinkedList<>());
            adjMap.get(j).add(i);
        }
        return true;
    }
}