Iterate Java Map with index
Asked Answered
P

4

12

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?

Parmentier answered 4/12, 2014 at 18:7 Comment(0)
H
17

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;
    }
    ...
}
Hippodrome answered 4/12, 2014 at 18:12 Comment(0)
W
4

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();
});
Weiweibel answered 19/10, 2020 at 14:44 Comment(0)
A
3

There is another simple solution:

int i = 0;
int mapSize = map.size();

for (Map.Entry<String, Integer> element : map.entrySet()) {
    String key = element.getKey();
    int value = element.getValue();

    ...

    i++;
}

You have the key, value, index, and the size.

Altagraciaaltaic answered 29/1, 2021 at 6:18 Comment(0)
T
2

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();
}
Tletski answered 4/12, 2014 at 18:14 Comment(2)
I think here is the time to start to indent your code.Lochia
@Lochia sorry about that :)Tletski

© 2022 - 2024 — McMap. All rights reserved.