0

I need to dump a list of somewhat complicated Java objects in YAML. To get the needed structure I first converted them into nested lists and maps. So it's kind of like:

- item 1
    name : value
    name : value
        - another list
        ...
- item 2
...

Or in eclipses debugger view where [...,...] is a list and {name:value,name:value} a map it looks something like [{item1={name:value, name:value[{anotherlist}]}item2=...]. It's a mess, but it's not that long and not that difficult to understand, just tedious.

The problem is a few of theses blocks are optional, so I get a few empty lists or null values:

- item 1
    null : null
    name : []
- item 2
and so on

Which is messy and can't be read in again. And I can't check one of the higher level lists or maps because they might contain empty lists, empty maps or nulls. I don't want to write if (value != null && !value.isEmpty) over and over again. As I see it I have 3 options:

  • I could technically modify the template, but I don't want to mess with that if I don't have to. I could go over the whole construct afterwards and take out all the nulls and empty constructs. But manually writing that would be long and nested and recursion with if (value.isList) and if (value.isMap) all the time doesn't sound great either.
  • I could write

    private Map putUnlessNullOrEmpty(Map, Name, Value) 
    private List addUnlessNullOrEmpty(List, Name, Value)
    

methods. That's what I did, but it looks very unjavaish.

  • It'd be great if I could add these methods to my lists and maps in that class. Or override/overload the put/add methods. I could write separate classes (or inner classes) extending the usual maps and lists, just another method. But that sounds kind of excessive.

I'm not that experienced with Java or programming in general yet. What do you think?

  • Just use [`Map.computeIfAbsent`](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-). Or [`Optional.ifPresent`](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#ifPresent-java.util.function.Consumer-) depending on the "end" of the relationship you are coming from. Or even better, simply use a YAML parser, like [Jackson](https://github.com/FasterXML/jackson-dataformat-yaml) to do this in a couple of lines... – Boris the Spider Feb 05 '16 at 17:51
  • Thanks for the answer. [Jackson](https://github.com/FasterXML/jackson-dataformat-yaml) or something similar sound good, the programs using just snakeyaml at the moment. But it's a small issue and I don't think it's worth adding a larger parser just for that. I don't think java 8 is available for `computeIfAbsend` or `Optional`, unfortunately. – d.jordanov Feb 05 '16 at 18:45

0 Answers0