从哈希映射返回键列表的方法取决于您使用的编程语言。以下是一些常见编程语言的示例:
- Python:hash_map = {'a': 1, 'b': 2, 'c': 3}
key_list = list(hash_map.keys())
- Java:import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("a", 1);
hashMap.put("b", 2);
hashMap.put("c", 3);
List<String> keyList = new ArrayList<>(hashMap.keySet());
}
}
- JavaScript:const hashMap = {'a': 1, 'b': 2, 'c': 3};
const keyList = Object.keys(hashMap);
- C#:using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
Dictionary<string, int> hashMap = new Dictionary<string, int>();
hashMap.Add("a", 1);
hashMap.Add("b", 2);
hashMap.Add("c", 3);
List<string> keyList = new List<string>(hashMap.Keys);
}
}
- PHP:$hashMap = ['a' => 1, 'b' => 2, 'c' => 3];
$keyList = array_keys($hashMap);
- Ruby:hash_map = {'a' => 1, 'b' => 2, 'c' => 3}
key_list = hash_map.keys
- Go:package main
import (
"fmt"
)
func main() {
hashMap := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
keyList := make([]string, 0, len(hashMap))
for key := range hashMap {
keyList = append(keyList, key)
}
}
- Swift:import Foundation
let hashMap: [String: Int] = ["a": 1, "b": 2, "c": 3]
let keyList = Array(hashMap.keys)
- Kotlin:fun main() {
val hashMap = mapOf("a" to 1, "b" to 2, "c" to 3)
val keyList = hashMap.keys.toList()
}
- Rust:use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::new();
hash_map.insert("a", 1);
hash_map.insert("b", 2);
hash_map.insert("c", 3);
let key_list: Vec<&str> = hash_map.keys().map(|k| k.as_str()).collect();
}
在这些示例中,我们创建了一个哈希映射(字典、映射或其他名称),并使用相应的方法从哈希映射中提取键列表。请注意,这些示例仅适用于特定的编程语言,因此您需要根据您的需求选择正确的示例。