[英]Numeric string sorting using Iterable<Component> in groovy
我想從Iterable<Component> components
中對版本進行排序。 Нow 當我在控制台中打印時,它會顯示以下結果:
artifact 1.0.1
artifact 1.0.10
artifact 1.0.11
artifact 1.0.12
artifcat 1.0.2
artifcat 1.0.3
artifcat 1.0.4
這是我的代碼
import org.sonatype.nexus.repository.storage.Component
import org.sonatype.nexus.repository.storage.Query
import org.sonatype.nexus.repository.storage.StorageFacet
def repoName = "artifact"
log.info("delete components for repository: " + repoName)
def repo = repository.repositoryManager.get(repoName)
def tx = repo.facet(StorageFacet).txSupplier().get()
try {
tx.begin()
Iterable<Component> components = tx.findComponents(Query.builder()
.where('version < ').param('1.1.0')
.build(), [repo])
tx.commit()
for(Component c : components) {
log.info("Name " + c.name() + " Version" + c.version())
}
} catch (Exception e) {
log.warn("Transaction failed {}", e.toString())
tx.rollback()
} finally {
tx.close()
}
可以按版本進行一些簡單的排序,如下所示:
def components = []
'''\
artifact 1.2.1
artifact 1.0.1
artifact 1.0.10
artifact 2.0.10
artifact 1.0.11
artifact 1.0.12
artifact 1.4.12
artifcat 1.0.2
artifcat 1.0.3
artifcat 1.0.4'''.splitEachLine( ' ' ){ name, version ->
components << [ name:name, version:version ]
}
// augment each component with numeric represenation of version
components.each{
it.versionNumeric = it.version.split( /\./ )*.toInteger().reverse().withIndex().sum{ num, pow -> 100.power( pow ) * num }
}
components.sort{ it.versionNumeric }*.version.join '\n'
印刷
1.0.1
1.0.2
1.0.3
1.0.4
1.0.10
1.0.11
1.0.12
1.2.1
1.4.12
2.0.10
另一個例子:
def components = '''\
artifact 1.2.1
artifact 1.0.1
artifact 1.0.10
artifact 2.0.10
artifact 10.2
artifact 1.0.11
artifact 1.0.12
artifact 1.4.12
artifcat 1.0.2
artifcat 1.0.3
artifcat 1.0.4
artifact 1.0.4.2'''.readLines()*.tokenize(' ').collect { name, version ->
[name: name, version: version]
}
def sorted = components.sort { a, b ->
def f = { it.version.tokenize('.')*.toInteger() }
[f(a), f(b)].transpose().findResult { ai, bi ->
ai <=> bi ?: null
} ?: a.version <=> b.version
}
sorted.each { c ->
println c.version
}
打印:
─➤ groovy solution.groovy
1.0.1
1.0.2
1.0.3
1.0.4
1.0.4.2
1.0.10
1.0.11
1.0.12
1.2.1
1.4.12
2.0.10
10.2
請注意,此解決方案還(至少或多或少)處理具有不同數量元素的版本,例如10.2
和1.0.4.2
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.