Guava: MutableGraph with nodeOrder 是反向插入

Guava: MutableGraph with nodeOrder that is inverse-insertion

我想从 Guava 创建一个 MutableGraph 类型的对象,如下所示:

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

当我使用迭代器从图中获取节点时,顺序是它们的插入。我需要让它们倒过来,这样我就可以通过

的一次调用来检索最后添加的顶点
subgraph.nodes().iterator().next()

Graph 在 map 中存储节点,在 Guava 中 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

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

如果您希望代码不为空图抛出 NoSuchElementException,请使用带默认值的重载,例如:

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

(上面还有Iterators counterparts种方法。)