Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate Java Map with index

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?

like image 313
Sam Joos Avatar asked Dec 04 '14 18:12

Sam Joos


2 Answers

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();
});
like image 67
Seyed Ali Roshan Avatar answered Sep 21 '22 13:09

Seyed Ali Roshan


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();
}
like image 30
Sarthak Mittal Avatar answered Sep 22 '22 13:09

Sarthak Mittal