Groovy / Java method to convert a nested view of a List String back to a list

I need to convert the string representation of a nested list back to a nested list (s) in Groovy / Java, for example.

String myString = "[[one, two], [three, four]]"
List myList = isThereAnyMethodForThis(myString)

I know that there is a Groovy.split method for separating strings by comma, and I could use regular expressions to identify nested lists between [and], but I just want to know if there is an existing method that can do this, or should I write this code myself.

I think the easiest would be a List constructor, which takes a String representation as an argument, but I haven't found anything like it.

+3
source share
2

Groovy, , :

String myString = "[['one', 'two'], ['three', 'four']]"
List myList = Eval.me(myString)

, , , , ...

class StringToList extends Binding {
  def getVariable( String name ) {
    name
  }
  def toList( String list ) {
    new GroovyShell( this ).evaluate( list )
  }
}

String myString = "[[one, two], [three, four]]"
List myList = new StringToList().toList( myString )

Binding Groovy " script, script script ."

, , ( ).

, GroovyShell , , , Shell.

, Shell one, two .., , , Binding.

...

Groovy, withDefault , .

, :

String myString = "[[one, two], [three, four]]"
Map bindingMap = [:].withDefault { it }
List myList = new GroovyShell( bindingMap as Binding ).evaluate( myString )

, Map ( withDefault) , , .

+7

. , "[" , , ",", , "]".

.

public int parseListString(String listString, int currentOffset, List list){
    while(currentOffset < listString.length()){
        if(listString.startsWith("[", currentOffset)){
            //If there is a [ we need a new List
            List newList = new ArrayList();
            currentOffset  = parseListString(listString, currentOffset+1, newList);
            list.add(newList);
        }else if(listString.startsWith("]", currentOffset){
            //If it a ], then the list is ended
            return currentOffset+1;
        }else{
            //Here we have a string, parse it until next ',' or ']'
            int nextOffset = Math.min(listString.indexOf(',', currentOffset), listString.indexOf(']', currentOffset));
            String theString = listString.substring(int currentOffset, int nextOffset);
            list.add(theString);

            //increment currentOffset
            currentOffset = nextOffset;
        }
    }
    return currentOffset;
}
+2

Source: https://habr.com/ru/post/1761683/


All Articles