Search code examples
javabukkit

Loading / Saving HashMap<String, String> , HashSet<String>


I would like to know how I can actually save and load the following HashMap and HashSet in the same file, /data.yml or /data.txt .. without them overwriting each other.

HashMap<String, String> teamByPlayer = new HashMap<String, String>();
HashSet<String> teamNames = new HashSet<String>();
HashSet<String> playersThatHaveDoneThis = new HashSet<String>();

String name = player.getName();
if (playersThatHaveDoneThis.contains(name)) {
//do stuff
} else {
// do stuff
playersThatHaveDoneThis.add(name);
}

This is what I've tried:

for (String str : plugin.getConfig().getKeys(true)) {
    int p = plugin.getConfig().getInt(str); 
    points.put(str, p); 
} 
plugin.saveConfig();

I want to know a way to save all those HashMap and HashSet ... Note: the example below is just for showing it.


Solution

  • I wrote two methods for you:

    public  static String convertHashMapToString(HashMap<String, String> h){
     String value = "";
     for(String s : h.keySet()){
      value += s + ":" + h.get(s) + ";";
     }
     return value;
    }
    public static HashMap<String, String> loadHashMapFromString(String saved){
     HashMap<String, String> value = new HashMap<String, String>();
     for(String s : saved.split(";")){
      value.put(s.split(":")[0], s.split(":")[1]);
     }
     return value;
    }
    

    I hope it works for you :)