Java map iteration with index

How can I iterate over a map to write content from a specific index to another.

Map<String, Integer> map = new LinkedHashMap<>();
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));

            for (String string : map.keySet()) {

                    bufferedWriter.write(string + " " + map.get(string));
                    bufferedWriter.newLine();

            }
            bufferedWriter.close();

I have two values ​​int, from and to, how can I now write, for example, from 10 to 100? Is it possible to iterate a map with an index?

+4
source share
2 answers

LinkedHashMappreserves the insertion order of records. Thus, you can try to create a list of keys and loops using the index:

List<String> keyList = new ArrayList<String>(map.keySet());
for(int i = fromIndex; i < toIndex; i++) {
    String key = keyList.get(i);
    String value = map.get(key);
    ...
}

Another way without creating a list:

int index = 0;
for (String key : map.keySet()) {
    if (index++ < fromIndex || index++ > toIndex) {
        continue;
    }
    ...
}
+8
source

You can increase the int variable along with this loop:

int i = - 1;
for (String string : map.keySet()) {
    i++;
    if (i < 10) {
        // do something
    } else {
        // do something else
    }
    bufferedWriter.write(string + " " + map.get(string)); // otherwise...
    bufferedWriter.newLine();
}
+1
source

All Articles