首页 > 解决方案 > 无法在 groovy 中的字符串列表上调用 remove() 方法

问题描述

我正在尝试删除字符串列表中某个索引处的字符串,但是我似乎无法在 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
}

我尝试了几种不同的方法,但它们似乎都不起作用。

标签: arraylistgroovy

解决方案


您可以处理与它的继任者成对的每个条目,而不是操纵列表...我相信这可以满足您的需求吗?

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 }

推荐阅读