Guava: MutableGraph with nodeOrder that is inverse-insertion Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Guava: MutableGraph with nodeOrder that is inverse-insertion without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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



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.)

We are here to answer your question about Guava: MutableGraph with nodeOrder that is inverse-insertion - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji