如何在 Java 中导航树状图
上面的示例显示了如何在树状图的所有元素中导航。首先,您可以通过调用 ketSet()它将键列表作为一组对象返回。通过读取集合的每个元素,可以从 TreeMap.
References:
Java 文档:Iterator
Java 文档:Map.Entry
import java.util.Set;运行此代码给出:
导入 java.util.TreeMap;
public class Parcours_treemap {
public static void main(String a[]){
TreeMap<字符串,字符串>tm = 新树状图<字符串,字符串>();
//添加键值对
tm.put(first”, element1”);
tm.put(第二”, 元素2”);
tm.put(第三”,element3”);
集<字符串>键 = tm.keySet();
for(String key: keys){
System.out.println(+key+” 的值为: +tm.get(key));
}
}
}
第二个的值为:element2
第一个的值为:element1
第三个的值为:element3
使用 Iterator 浏览树状图
在此例如,我们使用 Iterator 和 Map.Entry.import java.util.Iterator 浏览 TreeMpa 列表;此代码在执行后返回此结果:
导入 java.util.Set;
导入 java.util.TreeMap;
import java.util.Map;
public class TreeMap_iterator {
public static void main(String a[]){
// 创建 TreeMap
TreeMap<字符串,字符串>tmap = 新树状图<字符串,字符串>();
// 在 TreeMap
tmap.put(Key1”,element1”);
tmap.put(键2”,元素2”);
tmap.put(键3”,元素3”);
tmap.put(键4”,元素4”);
// 获取所有输入
Set set = tmap.entrySet();
// 获取迭代器浏览列表
迭代器 it = set.iterator();
// 显示键值对等节点
while(it.hasNext()) {
Map.Entry mentry = (Map.Entry)it.next();
System.out.print(键: ”+mentry.getKey() + - ”);
System.out.println(值:”+mentry.getValue());
}
}
}
key: Key1 - 值: element1
key: Key2 - 值: element2
key: Key3 - 值: element3
key: Key4 - 值:element4
References:
Java 文档:Iterator
Java 文档:Map.Entry