Search code examples
javacollectionsdictionaryiowriter

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?


Solution

  • 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;
        }
        ...
    }