java怎样获得字典的值
在Java中,可使用Map接口来表示字典。Map接口提供了多个方法来获得字典的值。
1. 使用get方法:使用get方法通过键获得对应的值。示例代码以下:
```java
Map
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
int value = dictionary.get("apple"); // 获得键"apple"对应的值
System.out.println(value); // 输出:1
```
2. 使用values方法:使用values方法获得字典中所有的值。示例代码以下:
```java
Map
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
Collection
System.out.println(values); // 输出:[1, 2, 3]
```
3. 使用entrySet方法:使用entrySet方法获得字典中所有的键值对,然后可以遍历键值对来获得值。示例代码以下:
```java
Map
dictionary.put("apple", 1);
dictionary.put("banana", 2);
dictionary.put("orange", 3);
Set
for (Map.Entry
String key = entry.getKey(); // 获得键
int value = entry.getValue(); // 获得值
System.out.println(key + ": " + value);
}
```
以上是经常使用的几种方法来获得字典的值,根据具体需求可以选择合适的方法来获得字典的值。
TOP