Fundamentals 4 min read

Topological Sorting of Directed Acyclic Graphs with Java Implementation Using Guava

This article explains the definition and properties of directed acyclic graphs (DAG), describes the basic topological sorting algorithm steps, and provides a complete Java implementation using Guava's MutableGraph class, illustrating the process with an example and its execution result.

Cognitive Technology Team
Cognitive Technology Team
Cognitive Technology Team
Topological Sorting of Directed Acyclic Graphs with Java Implementation Using Guava

In scheduling systems, tasks often have dependencies that are modeled using directed acyclic graphs (DAG) to facilitate ordering.

A DAG is a directed graph with no cycles; a topological ordering is a sequence of its vertices that satisfies two conditions: each vertex appears exactly once, and if vertex A precedes vertex B in the sequence, there is no path from B to A in the graph.

The basic topological sorting algorithm works as follows: (1) compute the indegree of each vertex from the adjacency matrix and collect vertices with indegree zero into a list zero; (2) output a vertex from zero and remove it together with all incident edges; (3) add any newly indegree‑zero vertices to zero; (4) repeat steps 2 and 3 until all vertices are output or no zero‑indegree vertex remains.

An example DAG yields the ordering {1, 2, 4, 3, 5} after sorting.

The article provides a complete Java implementation that uses Guava’s MutableGraph class to represent the DAG and performs the above algorithm.

package com.renzhikeji.demo;

import com.google.common.graph.GraphBuilder;
import com.google.common.graph.MutableGraph;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 认知科技技术团队
 * 微信公众号:认知科技技术团队
 */
public class TopologicalSorting {
    public static void main(String[] args) {
        MutableGraph<Integer> graph = GraphBuilder.directed().allowsSelfLoops(false).build();
        graph.putEdge(1, 2);
        graph.putEdge(1, 4);
        graph.putEdge(2, 4);
        graph.putEdge(2, 3);
        graph.putEdge(3, 5);
        graph.putEdge(4, 5);

        List<Integer> sortResult = new ArrayList<>(graph.nodes().size());

        while (true) {
            List<Integer> result = inDegreeZero(graph);
            if (result.isEmpty()) {
                break;
            }
            sortResult.addAll(result);
            for (Integer i : result) {
                graph.removeNode(i);
            }
        }

        System.out.println(sortResult);
    }

    private static List<Integer> inDegreeZero(MutableGraph<Integer> graph) {
        return graph.nodes().stream().filter(t -> graph.inDegree(t) == 0).collect(Collectors.toList());
    }
}

The program prints the sorted list [1, 2, 4, 3, 5], confirming the correct topological order.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaDAGGuavagraph algorithmsTopological Sorting
Cognitive Technology Team
Written by

Cognitive Technology Team

Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.