如何将 LinkedHashMap
滚动到特定键?像这样:
LinkedHashMap<String,String> queque = new LinkedHashMap<String,String>();
queque.put("uno","uno");
queque.put("due","due");
queque.put("tre","tre");
queque.put("quattro","quattro");
queque.put("cinque","cinque");
Iterator i = queque.entrySet().iterator();
while(i.next().getKey().equals(quattro)) {
System.out.print(i.getKey() + ": ");
System.out.println(i.getValue());
i.next();
}
最佳答案
你不必显式迭代(除非你真的想)通过键获取值:只需使用 get()
方法:
System.out.println("quattro" + ": " + queque.get("quattro"));
如果要打印直到某个值的所有值,可以执行以下操作:
Iterator i = queque.entrySet().iterator();
while(i.hasNext()) {
Map.Entry<String, String> me = i.next();
if (me.getKey() == "quattro") break;
System.out.println(me.getKey() + ": " + me.getValue());
}
或者,更优雅一点:
for (Map.Entry<String, String> me : queque.entrySet()) {
if (me.getKey() == "quattro") break;
System.out.println(me.getKey() + ": " + me.getValue());
}
再加点:
如果您不需要按添加顺序存储元素,请使用
HashMap
而不是LinkedHashMap
,因为前者更快。如果您想对存储元素进行排序,请使用TreeMap
(但请注意它比其他类型的Map
慢)。当您在 Java 中创建容器实例时,最好使用接口(interface)(例如
Map
、List
或Set
) 在赋值的左边,实现(如HashMap
、ArrayList
等)在右边,因为它为您提供更大的灵 active :如果您稍后决定更改同一接口(interface)的实现(例如,使用HashMap
而不是我上面建议的LinkedHashMap
),您只需要更改创建此容器的代码行,而不是更改使用此容器的所有位置。
关于java - 将 LinkedHashMap 滚动到键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27180005/