Saving a <String, Integer> HashMap

Discussion in 'Plugin Development' started by BDKing88, May 10, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    BDKing88

    Hello, I need some help saving a <String, Integer> HashMap. I'm making an API and I need a way to save this hashmap to a file or config. Any help is appreciated!
    Code:java
    1. package me.bdking00.c;
    2.  
    3. import java.util.HashMap;
    4.  
    5. import org.bukkit.entity.Player;
    6. import org.bukkit.plugin.java.JavaPlugin;
    7.  
    8. public class Main extends JavaPlugin {
    9.  
    10. public static HashMap<String, Integer> coins = new HashMap<>();
    11.  
    12. public void onEnable() {
    13. getConfig().options().copyDefaults(true);
    14. saveConfig();
    15. }
    16.  
    17. public void onDisable() {
    18. saveConfig();
    19. }
    20.  
    21. public void addCoins(Player p, int i) {
    22. Main.coins.put(p.getName(), Main.coins.get(p.getName()) + i);
    23. }
    24.  
    25. }
    26.  

    http://pastebin.com/iux4LP8H
     
  2. Offline

    LCastr0

    Not the best of the things to do, but you could send all the Strings to a list in your config, and then put a path for every string with the int.
     
  3. Offline

    BDKing88

    Yeah, the thing is, I don't know how to actually save the HashMap to the config :p
     
  4. Offline

    LCastr0

    try this:
    Code:java
    1. HashMap<String, Integer> test = new HashMap<String, Integer>();
    2.  
    3. public void getMap(){
    4. for(String s : this.getConfig().getStringList("StringList")){
    5. Integer value = this.getConfig().getInt(s);
    6. test.put(s, value);
    7. }
    8. }
    9.  
    10. public void saveMap(HashMap<String, Integer> map){
    11. List<String> l = new ArrayList<String>();
    12. for(Entry<String, Integer> e : map.entrySet()){
    13. String key = e.getKey();
    14. Integer value = e.getValue();
    15. if(!l.contains(key)){
    16. l.add(key);
    17. }
    18. this.getConfig().set(key, value);
    19. }
    20. this.getConfig().set("StringList", l);
    21. this.saveConfig();
    22. }
     
  5. Offline

    tryy3

Thread Status:
Not open for further replies.

Share This Page