arraylist - 无法在 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
}
我尝试了几种不同的方法,但它们似乎都不起作用。
解决方案
您可以处理与它的继任者成对的每个条目,而不是操纵列表...我相信这可以满足您的需求吗?
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 }
推荐阅读
- machine-learning - 如何将语音文件输入 RNN/LSTM 进行语音识别?
- javascript - 如何使 JS/Jquery 透视效果在模态中起作用?
- postgresql - 尽管使用了 NOT NULL 和 <> '',但仍出现空白行
- python-3.x - 在 route_id on-change 方法中创建销售订单行
- laravel - 在 Laravel 5 中限制文本列字符
- php - 使用“echo $image;”之间的有效区别是什么?和“回声 $image->getImageBlob();”
- python - IndexError:只有整数、切片(`:`)、省略号(`...`)
- c# - 发送ref参数时如何返回out参数?
- javascript - 获取复选框值并检查它们是否在数组中
- python - 如何向任何通用 SQL 查询添加额外的 WHERE 子句