java treemap的遍历
时间: 2023-12-31 16:22:23 浏览: 118
Java TreeMap是一种基于红黑树实现的有序映射,它提供了多种遍历方式,包括:
1. 遍历键
```java
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(1, "one");
treeMap.put(2, "two");
treeMap.put(3, "three");
for (Integer key : treeMap.keySet()) {
System.out.println(key);
}
```
2. 遍历值
```java
for (String value : treeMap.values()) {
System.out.println(value);
}
```
3. 遍历键值对
```java
for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
```
4. 使用迭代器遍历
```java
Iterator<Map.Entry<Integer, String>> iterator = treeMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
```
阅读全文