How'd you read an array of arrays of Integers from config?

Discussion in 'Plugin Development' started by DaDev, Feb 17, 2022.

Thread Status:
Not open for further replies.
  1. Offline

    DaDev

    I wanna read an array that looks like this from the config.yml:
    coords:
    [
    [1, 1, 1],
    [2, 2, 2],
    [3, 3, 3]
    ]

    So that what I end up with is something like List<Integer[]>
    And I don't know what to program to read this. How'd you do this?
     
  2. Offline

    timtower Administrator Administrator Moderator

    @DaDev Where does it come from?
     
  3. Offline

    KarimAKL

    @DaDev I assume what you have in your configuration file is a list of strings.

    I won't bother trying to explain this without code, so I'm just gonna spoon-feed you. However, I will try to explain along the way.
    Code:Java
    1. // Get the list of arrays from the config
    2. // The string representation (#toString) of this list will look like this:
    3. // "[[1, 1, 1], [2, 2, 2], [3, 3, 3]]"
    4. List<String> list = config.getStringList(/* your path */);
    5.  
    6. // Declare and initialize a 2d int array with the same size as the list
    7. // We will fill this array with your arrays
    8. int[][] array = new int[list.size()][];
    9.  
    10. // Loop the list of arrays
    11. for (int index = 0; index < list.size(); index++) {
    12. // Get the string representation of the array. This could look like:
    13. // "[1, 1, 1]"
    14. String string = list.get(index);
    15.  
    16. // Initialize the array at array[index]
    17. // First we remove the square brackets from the string
    18. // "1, 1, 1"
    19. // Then we split the string into a string array with the delimiter ", "
    20. // ["1", "1", "1"]
    21. // Then we map the stream to an IntStream by parsing all the strings in the array
    22. // Finally, we get an int array from the IntStream
    23. array[index] = Arrays
    24. .stream(string.substring(1, string.length() - 1).split(", "))
    25. .mapToInt(Integer::parseInt)
    26. .toArray();
    27. }
    28.  
    29. // That's it. Now you have a 2d int array containing your data.
    30. // We can print it using Arrays#deepToString(Object[])
    31. System.out.println(Arrays.deepToString(array));
    32. // "[[1, 1, 1], [2, 2, 2], [3, 3, 3]]"

    If you actually need a List<Integer[]> (or List<int[]>), then you can simply replace the 2d int array.
     
Thread Status:
Not open for further replies.

Share This Page