Get config path by a string in it

Discussion in 'Programming' started by CopyPaste, Apr 22, 2017.

  1. So, in config I have something like:
    Code (Text):
    PlayerName: String
    AnotherPlayerName: AnotherString
    ...
    How can I get the Player name if I only have the string?
     
  2. Iterate over getKeys(false) on that ConfigurationSection and check if the value of that key is the one you want
    Example (Java 7)
    Code (Text):
    private void findKeyByValue(String value, ConfigurationSection section) {
        for (String key : config.getKeys(false)) {
            if (config.getString(key).equals(value)) {
                return key;
            }
        }
    }
    Example (Java 8)
    Code (Text):
    private void findKeyByValue(String value, ConfigurationSection section) {
        return section.getKeys(false).stream()
            .filter(key -> config.getString(key).equals(value))
            .findAny().orElse(null);
    }
    If you want to look at the root of the config, call it like this
    Code (Text):
    FileConfiguration config = ...
    String key = findKeyByValue("YourStringValue", config);
    Or get the section by the path
    Code (Text):
    FileConfiguration config = ...
    ConfigurationSection section = config.getSection("my.players.section");
    String key = findKeyByValue("YourStringValue", section);
     
    #2 Jamezrin, Apr 22, 2017
    Last edited: Apr 22, 2017
  3. If this is Java 8 related then go to the spigot plugin dev page.