Iterate Java Map with index
this is a bit old but for those who want to use Map.forEach
can achieve the result like this:
AtomicInteger i = new AtomicInteger(0);
map.forEach((k, v) -> {
int index = i.getAndIncrement();
});
LinkedHashMap
preserves the order in which entries are inserted. So you can try to create a list of the keys and loop using an 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;
}
...
}
You can increase an int variable along with that 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();
}