1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add SortbyKeys for map

This commit is contained in:
dudaodong
2024-08-23 11:21:29 +08:00
parent 30971c1aab
commit 3e8c3bd396
5 changed files with 151 additions and 0 deletions

View File

@@ -56,6 +56,7 @@ import (
- [ConcurrentMap_Has](#ConcurrentMap_Has)
- [ConcurrentMap_Range](#ConcurrentMap_Range)
- [GetOrSet](#GetOrSet)
- [SortByKeys](#SortByKeys)
<div STYLE="page-break-after: always;"></div>
@@ -1522,4 +1523,41 @@ func main() {
// a
// b
}
```
### <span id="SortByKeys">SortByKeys</span>
<p>对传入的map根据key进行排序返回排序后的map。</p>
<b>函数签名:</b>
```go
func SortByKeys[K constraints.Ordered, V any](m map[K]V) (sortedKeysMap map[K]V)
```
<b>示例:<span style="float:right;display:inline-block;">[运行]()</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/maputil"
)
func main() {
m := map[int]string{
3: "c",
1: "a",
4: "d",
2: "b",
}
result := maputil.SortByKeys(m)
fmt.Println(result)
// Output:
// map[1:a 2:b 3:c 4:d]
}
```

View File

@@ -1538,4 +1538,41 @@ func main() {
// a
// b
}
```
### <span id="SortByKeys">SortByKeys</span>
<p>Sorts the map by its keys and returns a new map with sorted keys.</p>
<b>Signature:</b>
```go
func SortByKeys[K constraints.Ordered, V any](m map[K]V) (sortedKeysMap map[K]V)
```
<b>Example:<span style="float:right;display:inline-block;">[运行]()</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/maputil"
)
func main() {
m := map[int]string{
3: "c",
1: "a",
4: "d",
2: "b",
}
result := maputil.SortByKeys(m)
fmt.Println(result)
// Output:
// map[1:a 2:b 3:c 4:d]
}
```