使用索引迭代 Java Map

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27300962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:34:58  来源:igfitidea点击:

Iterate Java Map with index

javacollectionsmapiowriter

提问by Sam Joos

How can I iterate a Map to write the content from certain index to another.

如何迭代 Map 以将内容从某个索引写入另一个。

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?

我有两个 int 值,from 和 to,我现在怎么写,例如从 10 到 100?有没有可能用索引迭代地图?

回答by M Anouti

LinkedHashMappreserves the order in which entries are inserted. So you can try to create a list of the keys and loop using an index:

LinkedHashMap保留条目插入的顺序。因此,您可以尝试使用索引创建键列表和循环:

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

回答by Sarthak Mittal

You can increase an int variable along with that loop:

您可以在该循环中增加一个 int 变量:

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();
}