Skip to content

How to flatten dynamic yaml file using java

I want to parse dynamic yaml files using java into HashMap and access them using dot syntax (i.e “a.b.d”)

Given the following example.yml:

    c: "Hello, World"
    d: 600

And can fetch it as



Any idea How we can achieve this?



As Thorbjørn said in a comment, a HashMap is probably not the correct data structure for representing a YAML file.

You should try looking into tree structures instead.

Maybe something along the lines of:

public class Node {

  private final String name;
  private final Object value;
  private final Node parent;
  private final Collection<Node> children = new ArrayList<Node>();

  public Node(Node parent, String name) {
    this.parent = parent; = name;

  public Node getParent() {
    return this.parent;

  public String getName() {

  public Collection<Node> getChildren() {
    return this.children;

  public void addChild(Node child) {
    child.parent = this;


And then you just parse the YAML file line by line and construct nodes as you go, adding all subordinate nodes as children of the closest parent node.

Eventually you’ll have a populated tree structure, starting with the top Node and going down throughout every Node in the tree.

You could then write a method that can parse strings in the dot syntax you want and then navigate the tree structure accordingly to find the wanted Node.

Note that it’s not a good idea to store the values as Objects, you should implement some sort of value-wrapper like NumberValue (that stores the value as a double) and StringValue (that stores the value as a String), so that you don’t have to cast Objects to different types.

1 People found this is helpful