无法在Groovy中的字符串列表上调用remove()方法

时间:2019-03-29 17:13:13

标签: arraylist groovy

我试图在我的字符串列表中的某个索引处删除一个字符串,但是我似乎无法在Groovy中调用list.remove()方法。

public List getCassetteTypes(socket, numOfSlots){
 //get the cassettes layout
 sendCommand(socket, 'syst:layout? ')

 String systLayoutStr = readCommand(socket)
 //this String looks like: '1 ABC, 2 DEF, 3 SPN, ....'
    List listOfCassetteTypes = new ArrayList<String>()
 //I split the String at ',' because for each cassetteName, I want to remove the number before it
    listOfCassetteTypes = systLayoutStr.split(',')


    for(int i = 0; i < numOfSlots; i++){
      //remove any white spaces
        listOfCassetteTypes[i] = listOfCassetteTypes[i].trim()
      //remove the numerical value
        listOfCassetteTypes[i] = listOfCassetteTypes[i].replace((i + 1) + ' ', '')
        /* if the cassette name is 'SPN', 
      I want to remove it and append '-EXT' to the cassetteName before it,
      because 'SPN' means the previous slot is extended, 
      'SPN' itself isn't a cassette */
        if(listOfCassetteTypes[i].equalsIgnoreCase('spn')){
            listOfCassetteTypes[i - 1] = listOfCassetteTypes[i - 1].concat('-EXT')
   //this is what is not working for me, everything else is fine.
   listOfCassetteTypes = listOfCassetteTypes.remove(i)
        }
    }
    return listOfCassetteTypes
}

我尝试了几种不同的方法,但是似乎都没有。

1 个答案:

答案 0 :(得分:1)

除了操纵列表之外,您还可以与它的后继对象成对地处理每个条目...我相信这可以满足您的要求?

def layoutStr = '1 ABC, 2 DEF, 3 SPN, 4 GHI'

def splitted = layoutStr.split(',')
    *.trim()                        // remove white space from all the entries (note *)
    *.dropWhile { it ==~ /[0-9 ]/ } // drop until you hit a char that isn't a number or space
    .collate(2, 1, true)            // group them with the next element in the list
    .findAll { it[0] != 'SPN' }     // if a group starts with SPN, drop it
    .collect { 
        // If the successor is SPN add -EXT, otherwise, just return the element
        it[1] == 'SPN' ? "${it[0]}-EXT" : it[0]
    }

assert splitted == ['ABC', 'DEF-EXT', 'GHI']

跟进问题

只获取那些数字不是 SPN

def layoutStr = '1 ABC, 2 DEF, 3 SPN, 4 GHI'

def splitted = layoutStr.split(',')
    *.trim()                                       // remove white space from all the entries (note *)
    *.split(/\s+/)                                 // Split all the entries on whitespace
    .findResults { it[1] == 'SPN' ? null : it[0] } // Only keep those that don't have SPN

请注意,这是一个字符串列表,而不是整数列表...如果需要整数,则:

    .findResults { it[1] == 'SPN' ? null : it[0] as Integer }