Skip to content

Instantly share code, notes, and snippets.

@kinggoesgaming
Last active April 21, 2016 02:20
Show Gist options
  • Save kinggoesgaming/55a7b746e51823ecf7183c527c3d5505 to your computer and use it in GitHub Desktop.
Save kinggoesgaming/55a7b746e51823ecf7183c527c3d5505 to your computer and use it in GitHub Desktop.

List Values

Unlike the basic values, getting values from lists is slightly more involved, as multiple values are involved. The main getters for lists are getList(Function<Object, T>):List<T>, getList(Function<Object, T>, List<T>):List<T>, getList(TypeToken<T>):List<T>, getList(TypeToken<T>, List<T>):List<T>.

For the purpose of teaching the following sample will be used be used:

{
    "modules" : {
        "blockCheats" : {
            "enabled" : true,
            "counters" : [1,2,3,4, "hello", 1.22]
        }
    }
}

Where for basic values you can just do:

root.getNode("modules", "blockCheats", "enabled").getBoolean(false);

This cannot be done for lists. Instead you have do something like this:

root.getNode("modules", "counters").getList(new Function<Object, Integer>(
    @Override
    public Integer apply(Object input) {
        if (input instanceof String) {
            return (Integer) input;
        }
        return null;
    }
)

The above code will return a list containing [1,2,3,4]. This can also shortened down using lambda expression:

root.getNode("modules").getList(input -> return input instanceof Integer ? (Integer) input : null);

However you may notice that running same checks again and again may be inefficient and only potentially cause errors. Configurate provides a handy utility to handle that for you. The above example can be replaced by:

import ninja.leaping.configurate.Types;
root.getNode("modules","counters").getList(new Function<Object, Integer> {
    @Override
    public Integer apply(Object input) {
        return Types.asInt(input)
    }
}

Or simply:

import ninja.leaping.configurate.Types;
root.getNode("modules", "counters").getList(Types::asInt);
@Wolfizen
Copy link

Repetition of "involved" in first paragraph.

Add an explanation of why "you have to do something like this". Ex: Lists are stored as List and each element must be converted to the desired type.

For the Types.asInt() example, no need to provide another example of an anonymous class, as there already is an example above (lambdas are preferred). Or alternatively, the lambda example for the first impl. could be removed, and the second anon. class would be a continuation/revision of the previous one.

@ryantheleach
Copy link

If you are going to explain iterating over a list, maybe explain iterating over a map as well?

@kinggoesgaming
Copy link
Author

@ryantheleach is there a getMap() method too :O

@Wolfizen sure this my first draft i am still modifying it. 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment