I am trying to implement a method that removes dead-ends from an RDF graph
Iterator<String> iter = rdfGraph.getVertices().iterator();
while(iter.hasNext()){
String x = iter.next();
if(rdfGraph.outDegree(x)==0){
iter.remove();
}
}
Whenever i run this i get a java.lang.UnsupportedOperationException. How can I fix my code.
The iterator's remove() method is optional. The javadoc mentions that when it's not supported, it will throw an UnsupportedOperationException:
Throws:
UnsupportedOperationException - if the remove operation is not supported by this iterator
Based on the discussion in adding a node to a collection using JUNG2, I'd assume that getVertices() returns a an unmodifiable collection, in which case the iterator wouldn't support remove(). Note that the javadoc for getVertices() says that the method returns a view of the vertices. It doesn't say that adding or removing from the collection adds or removes vertices from the graph, or that adding or removing vertices from the collection is even possible.
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.
Instead of iter.remove(), it probably makes more sense to use rdfGraph.removeVertex(x).
But, based on your comment
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?
It sounds like you either need to go through the vertices and create a new collection of which ones you want to remove, and then remove them after you're done iterating through the vertices. Alternatively, you could create a new collection of all the vertices and then remove them as you go through. E.g.,
new ArrayList<>(rdfGraph.getVertices()).stream()
.filter(v -> rdfGraph.outDegree(x) == 0)
.forEach(rdfGraph::removeVertex);
The use of ArrayList isn't important there; you just need some new collection that's not connected to the original graph.