Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to parse an arbitrarily nested array in a String, in this format: [3,[4,3],5], to a List(of lists, of lists...)

My example, once parsed, would be a list that looks something like this:

List(3, List(4, 3), 5)

I wrote some code (in the previous edits of this question), but none of my drafts worked. Could I have either a sample implementation or some pseudo-code?

share|improve this question
6  
It's kind of funny that my code uses a stack, has a StackOverflowException, and I posted it on StackOverflow.com –  Kyranstar Jul 22 at 22:38
    
what is expected outcome here? If I know, I may post some ideas later –  Kick Buttowski Jul 22 at 22:42
    
Let us continue this discussion in chat. –  Kick Buttowski Jul 23 at 0:47
    
BTW, that input is JSON. There are ready-made JSON parsers that will parse into a List containing another List just as you suggest. See json.org. –  Hot Licks 2 days ago

1 Answer 1

up vote 1 down vote accepted

Parsing a nested-array to such a String is rather simple:

Arrays.deepToString(array).replace(" ", "");

Converting this String to an infinitely nested-list is a bit more tricky. The easiest solution would probably be to use recursion:

/**
 * The following code is only for demonstration purposes.
 * It does neither do any validation on the input String 
 * nor work with more than one digit numbers.
 */

static int index = 0; // the position in the String

Object buildList(String nestedList) {
    List<Object> list = new ArrayList<>();

    while (index < nestedList.length()) {
        char c = nestedList.charAt(index++);

        if (c == '[') // add a sub-list via a recursive call
                list.add(buildList(nestedList));
        else if (c == ']') // stop building the list
                 break;
        else if (c == ',') {} // do nothing
        else // add an element to the list
            list.add(c);
    }

    return list;
}

Example call:

System.out.println(buildList("[3,[4,3],5]")); // prints [3, [4, 3], 5]


Note:

Even though the above code does what (at least I think) you want to achieve, it may not be advisable to use such a data-structure in practice, since the access to the nested-lists is quite complicated and involves some casting.

A better solution would probably be to use some kind of tree-datastructure where each node has a list of values including links to other nodes. (see: http://en.wikipedia.org/wiki/Tree_(data_structure))

share|improve this answer
    
Thanks! This was super helpful. –  Kyranstar 14 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.