Search code examples
scalaimmutabilitygremlinimmutable-collections

Most idiomatic way to iterate through and add to set functionally


I'm using Gremlin to iterate through a GraphTraversal object and retrieve the vertices.

Here's what I'm working with:

def getVertexSet(vIter: GraphTraversal[Vertex, Vertex]): Set[Vertex] = {
  val s = mutable.HashSet.empty[Vertex]
  vIter.forEachRemaining(v => s.add(v))
  s.toSet
}

I'd like to be able to do this without converting from a mutable collection to an immutable collection. I don't know if that's possible with an iterator. The Scala way to do this is probably using tail recursion but I'm not sure there's any performance benefit to that and at that point, a single conversion to immutable at the end is probably more readable anyways.

Also, if there's a better way to collect all the vertices from a traversal, I'm open to that optimization as well.


Solution

  • If you are okay with using Scala's Set instead of Java's, go with:

    import collection.JavaConverters._
    
    def getVertexSet(vIter: GraphTraversal[Vertex, Vertex]): Set[Vertex] = {
        vIter.asInstanceOf[java.util.Iterator[Vertex]].asScala.toSet
    }
    

    Try it out!

    You can still call .asJava on the Set[Vertex] later on if you really need a Java Set.