Close

How to load List in SnakeYaml?

[Last Updated: Jun 4, 2018]

In this tutorial, we will learn how to load a YAML list in Java.

According to YAML specifications list elements have a leading hyphen (-) and each element is on a new line.

Examples

Loading a List from YML file

src/main/resources/fruits.yml

- Apple
- Banana
- Orange
public class LoadList {
  public static void main(String[] args) throws IOException {
      loadFromFile("/fruits.yml");
  }

  private static void loadFromFile(String path) throws IOException {
      System.out.printf("-- loading from %s --%n", path);
      Yaml yaml = new Yaml();
      try (InputStream in = LoadList.class.getResourceAsStream(path)) {
          Iterable<Object> itr = yaml.loadAll(in);
          for (Object o : itr) {
              System.out.println("Loaded object type:" + o.getClass());
              System.out.println(o);
          }
      }
  }
}

Output

-- loading from /fruits.yml --
Loaded object type:class java.util.ArrayList
[Apple, Banana, Orange]

Loading multiple Lists

Multiple lists can be loaded in a Map with List values.

src/main/resources/fruitsGroup.yml

Morning:
 - Apple
 - Banana
 - Pear

Evening:
 - Orange
 - Grape
 - Pineapple
public class LoadMapList {
  public static void main(String[] args) throws IOException {
      loadFromFile("/fruitsGroup.yml");
  }

  private static void loadFromFile(String path) throws IOException {
      System.out.printf("-- loading from %s --%n", path);
      Yaml yaml = new Yaml();
      try (InputStream in = LoadMapList.class.getResourceAsStream(path)) {
          Iterable<Object> itr = yaml.loadAll(in);
          for (Object o : itr) {
              System.out.println("Loaded object type:" + o.getClass());
              Map<String, List<String>> map = (Map<String, List<String>>) o;
              System.out.println("-- the map --");
              System.out.println(map);
              System.out.println("-- iterating --");
              map.entrySet().forEach((e) -> {
                  System.out.println("key: " + e.getKey());
                  System.out.println("values:");
                  List<String> list = e.getValue();
                  for (String s : list) {
                      System.out.println(s);
                  }
              });
          }
      }
  }
}

Output

-- loading from /fruitsGroup.yml --
Loaded object type:class java.util.LinkedHashMap
-- the map --
{Morning=[Apple, Banana, Pear], Evening=[Orange, Grape, Pineapple]}
-- iterating --
key: Morning
values:
Apple
Banana
Pear
key: Evening
values:
Orange
Grape
Pineapple

Example Project

Dependencies and Technologies Used:

  • snakeyaml 1.18: YAML 1.1 parser and emitter for Java.
  • JDK 1.8
  • Maven 3.3.9

Yaml List Examples Select All Download
  • yml-simple-lists
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • LoadMapList.java
          • resources

    See Also