How can I iterate a Map to write the content from certain 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 int values, from and to, how can I now write for example from 10 to 100? is there any possibility to iterate the 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();
});
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();
}
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