Search code examples
scalaiohashset

how to save HashSet into a plain text file in Scala


For example, I have a HashSet and want to save it to file like txt or csv and so on.

val slotidSet: util.HashSet[String] = new util.HashSet[String](1)
slotidSet.add("100")
slotidSet.add("105")
slotidSet.add("102")
slotidSet.add("103")

How to save this HashSet into a plain text file?
Thanks in advance.


Solution

  • Something like this should do the work

    import java.nio.file.{Files, Paths}
    import java.util
    
    Files.write(Paths.get("file.txt"), slotidSet.asScala.mkString(",").getBytes)
    

    Output is

    100,102,103,105
    

    Now it's just up to you to choose format, in this case all the elements are just concatenated with ,. In cases where you need to work with files in Scala/Java, Java NIO is a good place to start.