for each遍历treemap
时间: 2023-11-08 09:10:14 浏览: 109
可以使用Java 8中的forEach方法来遍历TreeMap中的所有元素。
例如:
```
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(1, "One");
treeMap.put(2, "Two");
treeMap.put(3, "Three");
treeMap.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
```
输出:
```
Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
```
此外,也可以使用迭代器来遍历TreeMap中的所有元素。例如:
```
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(1, "One");
treeMap.put(2, "Two");
treeMap.put(3, "Three");
Iterator<Map.Entry<Integer, String>> iterator = treeMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
```
输出:
```
Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three
```
阅读全文