One of my program reads a file and does some processing and builds an in-memory hash set. I would like to store this built hash set as such in a file, so that another program can read it off later on as such and take the whole image in its in-memory data structure hash set. How to achieve this?
Have a look at serialization.
Here's an example:
String filename = "savedHashSet.dat"; // Create it Set<String> someStrings = new HashSet<String>(); someStrings.add("hello"); someStrings.add("world"); // Serialize / save it ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename)); oos.writeObject(someStrings); ... ... ... // Deserialize / load it ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename)); Set<String> aNewSet = (HashSet<String>) ois.readObject();
Note that the objects you store in the HashSet needs to be serializable too. Personally, I usually rely on "manual" serialization. If for instance your HashSet contains primitive types, Strings, or lists of Strings or something else which is easy enough to "manually" write to disk, I'd probably consider doing that.