Search code examples
javaguavagraph-theory

Guava: MutableGraph with nodeOrder that is inverse-insertion


I want to create an object of type MutableGraph from Guava, like this:

MutableGraph<Integer> subgraph = GraphBuilder.undirected().nodeOrder(ElementOrder.insertion()).build();

When I use an iterator to get the nodes from the graph, the order is their insertion. I need to get them in reverse, so that I can retrieve that last added vertex with one call of

subgraph.nodes().iterator().next()

Solution

  • Graph stores nodes in map under the hood, and for ElementOrder.insertion() it's LinkedHashMap. For Graph#nodes() keySet() of such map is used, so there's no better way to fetch last value other than iterating over all elements and returning the last one. Luckily there's a helper method Iterables#getLast(Iterable) for that in Guava:

    Integer last = Iterables.getLast(subgraph.nodes());
    

    If you want the code not to throw NoSuchElementException for empty graphs, use overload with default value, such as:

    Integer last = Iterables.getLast(subgraph.nodes(), null);
    

    (There're also Iterators counterparts of methods above.)