溫馨提示×

java如何獲取字典的值

小億
447
2023-08-03 22:12:39
欄目: 編程語言

在Java中,可以使用Map接口來表示字典。Map接口提供了多個方法來獲取字典的值。

  1. 使用get方法:使用get方法通過鍵獲取對應的值。示例代碼如下:
Map<String, Integer> dictionary = new HashMap<>();
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
int value = dictionary.get("apple"); // 獲取鍵"apple"對應的值
System.out.println(value); // 輸出:1
  1. 使用values方法:使用values方法獲取字典中所有的值。示例代碼如下:
Map<String, Integer> dictionary = new HashMap<>();
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
Collection<Integer> values = dictionary.values(); // 獲取字典中所有的值
System.out.println(values); // 輸出:[1, 2, 3]
  1. 使用entrySet方法:使用entrySet方法獲取字典中所有的鍵值對,然后可以遍歷鍵值對來獲取值。示例代碼如下:
Map<String, Integer> dictionary = new HashMap<>();
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
Set<Map.Entry<String, Integer>> entrySet = dictionary.entrySet(); // 獲取字典中所有的鍵值對
for (Map.Entry<String, Integer> entry : entrySet) {
String key = entry.getKey(); // 獲取鍵
int value = entry.getValue(); // 獲取值
System.out.println(key + ": " + value);
}

以上是常用的幾種方法來獲取字典的值,根據具體需求可以選擇適合的方法來獲取字典的值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女