Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 pairs.

Is there anyway to do this?

like image 326
pm13 Avatar asked Feb 28 '26 12:02

pm13


1 Answers

A Map doesn't in general maintain an order of the keys. You'll need to use

  • A NavigableMap, such as TreeMap. 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
like image 91
aioobe Avatar answered Mar 03 '26 00:03

aioobe