groovy のリストから最後の要素以外をすべて削除するきちんとした方法を見つけようとしていますが、私が試したすべてのことは少し複雑すぎるようです。もっときちんとした方法はありますか?
失敗:java.util.ConcurrentModificationException
void removeAllButLastInPlace(list) {
if(list.size() > 1) {
def remove = list[0..-2]
remove.each { list.remove(it) }
}
}
失敗:java.lang.CloneNotSupportedException: java.util.ArrayList$SubList
void removeAllButLastInPlace(list) {
if(list.size() > 1) {
def remove = list[0..-2].clone()
remove.each { list.remove(it) }
}
}
動作しますが、リストの構築は不要のようです
void removeAllButLastInPlace(list) {
if(list.size() > 1) {
def remove = [] + list[0..-2]
remove.each { list.remove(it) }
}
}
動作しますが、少し難解なようです
void removeAllButLastInPlace(list) {
(list.size() - 1).times { list.remove(0) }
}
WORKS、おそらく最も「正しい」
void removeAllButLastInPlace(list) {
list.retainAll { list.lastIndexOf(it) == list.size() - 1 }
}
コードは次のテストを満たす必要があります。
list = []
removeAllButLastInPlace(list)
assert list == []
list = ['a']
removeAllButLastInPlace(list)
assert list == ['a']
list = ['a', 'b']
removeAllButLastInPlace(list)
assert list == ['b']
list = ['a', 'b', 'c']
removeAllButLastInPlace(list)
assert list == ['c']