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 pairs.
Is there anyway to do this?
A Map doesn't in general maintain an order of the keys. You'll need to use
NavigableMap, such as TreeMap. Preferable if your keys have a natural order.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With