使用 Jung 去除 RDF 图死胡同

Removing RDF graph dead-ends using Jung

我正在尝试实现一种从 RDF 图中删除死胡同的方法

Iterator<String> iter = rdfGraph.getVertices().iterator();  
    while(iter.hasNext()){
        String x = iter.next();
        if(rdfGraph.outDegree(x)==0){

            iter.remove();
        }

    }

每当我 运行 这个我得到一个 java.lang.UnsupportedOperationException。我该如何修复我的代码。

迭代器的remove()方法是可选的。 javadoc 提到当它不受支持时,它会抛出一个 UnsupportedOperationException:

Throws:

UnsupportedOperationException - if the remove operation is not supported by this iterator

根据 adding a node to a collection using JUNG2 中的讨论,我假设 getVertices() returns 是一个不可修改的集合,在这种情况下,迭代器将不支持 remove()。请注意,getVertices() 的 javadoc 表示方法 returns 是顶点的 view。它并没有说在集合中添加或删除会在图中添加或删除顶点,或者甚至可以在集合中添加或删除顶点。

getVertices Collection<V> getVertices()

Returns a view of all vertices in this graph. In general, this obeys the Collection contract, and therefore makes no guarantees about the ordering of the vertices within the set.

而不是iter.remove(),使用rdfGraph.removeVertex(x)可能更有意义.

但是,根据您的评论

I used rdfGraph.removeVertex(x) initially but i got a java.util.ConcurrentModificationException. any idea on how I could bypass this without using an iterator?

听起来您要么需要遍历顶点并创建一个新集合,其中包含您要删除的顶点,然后在遍历顶点后删除它们。或者,您可以创建一个包含 所有 个顶点的新集合,然后在遍历过程中将它们移除。例如,

new ArrayList<>(rdfGraph.getVertices()).stream()
  .filter(v -> rdfGraph.outDegree(x) == 0)
  .forEach(rdfGraph::removeVertex);

ArrayList 的使用在那里并不重要;您只需要一些未连接到原始图形的新集合。