Search code examples
javayamlbukkit

How to get ordered HashMap from YAML?


I'm trying to retrieve a Map from my config.yml file, but cannot find a way to keep the key order previously set.

classes:
 beginner: 1000
 proplayer: 2000
 admin: 5000

I know that classes's keyset gets me a Map, but the order is not as the display shows.

I need it to be in order because it's the order of classes that the player will upgrade to. So if he's beginner, he'll need to upgrade to proplayer, and so on.

I need some way to sort it out, so I can get that beginner is at index 0, in order to guess which is the next class the player will move to, in this case, proplayer (index 1), but I also need to retrieve the int value of the class, in order to charge the player the amount from the class he's moving to.


Solution

  • Ordered mappings in YAML can be specified like this:

    classes: !!omap
      - beginner: 1000
      - proplayer: 2000
      - admin: 5000
    

    See Example 2.26. Ordered Mappings in YAML Specification (1.0, 1.1 or 1.2)

    Please note that it doesn't have to be supported by your YAML parser, but chances are it is (SnakeYAML does support it).
    The actual type that will be used for the result is also specific to your YAML parser, but should map to most natural ordered map type in the language.