ts获取Map的第i个key
要获取Map的第i个key,我们可以使用以下步骤:
- 将Map的key转换为一个数组,使用
Object[] keys = map.keySet().toArray();来获取Map的所有key,并将其转换为一个数组。 - 使用
keys[i]来获取第i个key。
以下是一个完整的示例代码:
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Key1", 1);
map.put("Key2", 2);
map.put("Key3", 3);
map.put("Key4", 4);
String key = getKeyAtIndex(map, 2);
System.out.println("Key at index 2: " + key);
}
public static <K, V> K getKeyAtIndex(Map<K, V> map, int index) {
Object[] keys = map.keySet().toArray();
return (K) keys[index];
}
}
输出结果:
Key at index 2: Key3
``
原文地址: https://www.cveoy.top/t/topic/iVbs 著作权归作者所有。请勿转载和采集!