How do I scroll a LinkedHashMap
to a specific key? Something like this:
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();
}
You don't have to explicitly iterate (unless you really want to) to get the value by key: just use
get()
method:If you want to print all the values up to the certain one, you can do the following:
Or, a little more elegant:
Couple more points:
If you do not need to store the elements in the order they were added, use
HashMap
rather thanLinkedHashMap
, since former is faster. If you want store elements sorted, useTreeMap
(but beware it is slower than the other types ofMap
).When you create instance of container in Java, you are better off using interface (like
Map
,List
orSet
) in the left part of assignment and implementation (likeHashMap
,ArrayList
etc.) in the right part since it gives you much more flexibility: in case you later on decide to change the implementation of the same interface (e.g. useHashMap
instead ofLinkedHashMap
as I suggested above), you only need to change one line of your code where you create this container, rather than change all places where this container is used.