使用Iterator及其values()
方法迭代TreeMap的值。
让我们首先创建一个TreeMap并添加一些元素-
TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"PHP"); m.put(2,"jQuery"); m.put(3,"JavaScript"); m.put(4,"Ruby"); m.put(5,"Java"); m.put(6,"AngularJS"); m.put(7,"ExpressJS");
遍历值-
Collection res = m.values(); Iterator i = res.iterator(); while (i.hasNext()) { System.out.println(i.next()); }
以下是迭代值的完整示例-
import java.util.*; public class Demo { public static void main(String args[]) { TreeMap<Integer,String> m = new TreeMap<Integer,String>(); m.put(1,"PHP"); m.put(2,"jQuery"); m.put(3,"JavaScript"); m.put(4,"Ruby"); m.put(5,"Java"); m.put(6,"AngularJS"); m.put(7,"ExpressJS"); System.out.println("TreeMap Elements..."); Collection res = m.values(); Iterator i = res.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }
输出结果
TreeMap Elements... PHP jQuery JavaScript Ruby Java AngularJS ExpressJS