Java iterate map from a certain index
I have a map created from a json string that is sorted in the order I need to parse in.
If there is a key at index 6 (7th key), I want to be able to iterate from this key to the end of the map and do what processing I need with these key/value 开发者_如何学JAVApairs.
Is there anyway to do this?
A Map
doesn't in general maintain an order of the keys. You'll need to use
- A
NavigableMap
, such asTreeMap
. Preferable if your keys have a natural order. - A
LinkedHashMap
which is a map implementation which preserves the insertion order.
Example snippet (LinkedHashMap):
Map<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
map.put(5, "five");
map.put(6, "six");
map.put(7, "seven");
map.put(8, "eight");
map.put(9, "nine");
int index = 0;
for (Integer key : map.keySet()) {
if (index++ < 6)
continue;
System.out.println(map.get(key));
}
// Prints:
// seven
// eight
// nine
Example snippet (TreeMap):
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
map.put(5, "five");
map.put(6, "six");
map.put(7, "seven");
map.put(8, "eight");
map.put(9, "nine");
for (Integer key : map.tailMap(6).keySet())
System.out.println(map.get(key));
// Prints
// six
// seven
// eight
// nine
The Map interface doesn't allow direct access by index. The best you can do is something like:
Map m;
....
int count 0;
for(object el : m){
if(count++ < 6) continue;
//do your stuff here
}
This assumes that your Map implementation is sorted - otherwise there is no guaranteed order when enumerating.
Depending on the underlying map implementation, the order has already been lost when it was parsed.
LinkedHashMap is the beast you are after - the Linked part gives you your predictable iteration order.
精彩评论