Home > database >  How can I grab a value from an ArrayList nested in a LinkedHashMap?
How can I grab a value from an ArrayList nested in a LinkedHashMap?

Time:11-26

I currently have a yaml file that looks like this:

description: this-apps-config
options:
  - customer: joe
    id: 1
    date: 2022-01-01
    print: False
  - customer: jane
    id: 2
    date: 2022-01-02
    print: True

I am able to successfully read this in using snakeyaml:

Yaml yaml = new Yaml();
InputStream inputStream = new FileInputStream(new File("file.yml"));
Map<String, Object> data = yaml.load(inputStream);
System.out.println(data);

The above code retrieves everything as a LinkedHashMap with the options being ArrayList of another HashMap that looks like this:

{description=this-apps-config, options=[{customer=joe, id=1, date=2022-01-01, print=False}, {customer=jane, id=2, date=2022-01-02, print=True}]}

My question is, how do I get the print value in each of the options? The closest I've gotten is doing:

ArrayList<Object> al = new ArrayList<>()
al.add(data.get("options"))

This only gets me that first options ArrayList though. Not sure how to get deeper.

Thanks

CodePudding user response:

YAML allows you to load a file into a custom class, and supports top-level types that fields of other types, including collections. Try something like the following:

public class MyYaml {

    private String description;
    private List<Customer> options;

    // getters and setters
}

public class Customer {

    private String customer;
    private int id;
    private Date date;
    private boolean print;

    // getters and setters
}

And then where you want to load the file:

Yaml yaml = new Yaml();
InputStream inputStream = this.getClass()
 .getClassLoader()
 .getResourceAsStream("myFile.yaml");
MyYaml myYaml = yaml.load(inputStream);

Here is a relevant tutorial that might help you.

  • Related